我有一个用于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/