将c库功能暴露给节点

时间:2015-07-30 15:11:17

标签: c node.js node-gyp

我一直在我的节点项目中使用c库。经过一点点调查后,我找到了node-gyp。

我成功地能够执行示例但是当我尝试在代码中使用第三方c库函数时,它给了我运行时的链接错误。

图书馆可以在http://bibutils.refbase.org/bibutils_3.40_src.tgz

找到

我独立编译了库以获得* .a对象

我正在使用以下示例 https://github.com/nodejs/node-addon-examples/tree/master/5_function_factory/node_0.12

所以我有以下问题,因为我可以推断

  • 我要将bibutils从make转换成gyp吗?
  • 我应该将每个源文件转换为与V8一起使用吗?我不知道该怎么做。
  • 如何轻松地将此项目链接到使用node-gyp并降低噪音?

有关脚本的详细信息可以在下面找到。 bibutils文件夹与addon.cc一起放置

binding.gyp看起来像

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ],
      "include_dirs": ["bibutils/lib"],
      "library_dirs": ["bibutils/lib/libbibutil.a","bibutils/lib/libbibprogs.a"]
    }
  ]
}

修改了addon.cc

#include <node.h>
#include "bibutils.h"
#include "bibprogs.h"

using namespace v8;

void MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
      /****This is not production code just to check the execution***/
      bibl b;   
      bibl_init( &b );
      bibl_free( &b );
      /**************************************************************/
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  args.GetReturnValue().Set(fn);
}

编制结果

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ npm install

> function_factory@0.0.0 install /home/user1/node-addon-examples/5_function_factory/node_0.12
> node-gyp rebuild

make: Entering directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'
  CXX(target) Release/obj.target/addon/addon.o
  SOLINK_MODULE(target) Release/obj.target/addon.node
  COPY Release/addon.node
make: Leaving directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'

执行时

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ node addon.js
node: symbol lookup error: /home/user1/node-addon-examples/5_function_factory/node_0.12/build/Release/addon.node: undefined symbol: _Z9bibl_initP4bibl

调试信息:

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ nm -C build/Release/addon.node | grep bibl_init
                 U bibl_init(bibl*)

1 个答案:

答案 0 :(得分:1)

问题是C ++和C之间的通信。在上面的例子中,C头文件包含在C ++代码中。编译期待C ++代码。因此,编译链接器由于编译代码不匹配而被阻塞。

所以我使用extern“C”指令通过以下代码告诉编译器C头文件。

package springWeb;


import org.springframework.stereotype.Component;

//@Component
public class UserServiceImpl implements UserService {

    @Override
    public void service() {
        System.out.println ("Service running...");
    }

}