javascript - 如何在 typescript 中使用C插件

标签 javascript node.js typescript node.js-addon

我有一个用于nodejs的c插件(使用napi),我可以在js代码中正确运行它。现在我想在 typescript 中使用它,我尝试编写一个.d.ts文件,但总是失败。我该怎么办正确写入 d.ts 文件吗? c 插件是一个 helloworld 代码,如下所示:

#include <node_api.h>
#include <stdio.h>


napi_value Helloworld(napi_env env, napi_callback_info info)
{
    napi_status status;

    size_t argc = 1;
    napi_value argv[1];
    status = napi_get_cb_info(env, info, &argc, argv, 0, 0);
    if(status != napi_ok )
    {
        napi_throw_type_error(env,"", "Wrong number of arguments");
        status = napi_get_undefined(env, argv);
    }
    printf("Hello\n");
    return NULL;
}

napi_value Init(napi_env env, napi_value exports)
{
    napi_status status;
    napi_property_descriptor des =
       { "helloworld", 0, Helloworld, 0, 0, 0, napi_default, 0 };
    status = napi_define_properties(env, exports, 1, &desc);
    return exports;
}

NAPI_MODULE(addon, Init)

js代码是这样的:

//this can run
const addon = require("../1/build/Release/addon");
addon.helloworld();

js 代码可以运行。现在我想在 typescript 中执行此操作,我如何编写 .d.ts 文件以及如何在 typescript 中运行它?谢谢。 我尝试过一些但失败了:

//this is fail code    
declare module "addon" {
      function helloworld():string 
      export = addon
    }

    /*
    const addon = require('./addon')
    declare  module 'addon'{
      export function addon.helloworld():string 
    }
    export function addon.echo(input: string):string
    export function echo {
    } = addon.echo */
    /* export = helloworld
    declare function helloworld (): string
     */
    /*
    export = MyFunction;
    declare function MyFunction(): string;
    */

    /* const addon = require('./addon')
    export default module 'addon' {
      export function helloworld():string
    }  */
    /* 
    const addon = require('./addon')
    export function helloworld():string
     */

最佳答案

尝试在'../1/build/Release/'文件夹中添加addon.d.ts文件,内容应为:

export function helloworld (): string

您可以查看此问题以了解更多详细信息:https://github.com/Microsoft/TypeScript/issues/8335

关于javascript - 如何在 typescript 中使用C插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50013708/

相关文章:

javascript - 使用按钮编辑表格行

javascript - 保存目标时,Internet Explorer 将 TXT 文件另存为 HTM

node.js - GraphQL - POST 正文丢失。你忘记使用 body-parser 中间件了吗?

angularjs - 如何在我的项目中使用 Bower 包组件

javascript - 将数组内的数组展平

javascript - Vue Router推送错误: Avoided redundant navigation to current location

javascript - 如何正确地将 json 传递给 View

java - 获取列表项中当前 ID 的值

node.js - 我如何使用带有请求或任何东西的node.js通过http代理通过https获取数据

Javascript - 从对象列表中获取最大数量,每个对象都有一个数字属性