swig - c++ to javascript

swig - c++ to javascript

本文关键字:javascript to c++ swig      更新时间:2023-10-16

我正试图使用我的cpp文件中的swig构建一个简单的javascript模块。我运行了所有正确的命令,但似乎什么都不起作用。这是我的.h文件

#pragma once
class Die
{
public:
Die();
Die(int a);
~Die();
int foo(int a) ;
Die* getDie(int a);
int myVar;
};

我的.cpp文件:

#include <iostream>
#include "example.h"
int Die::foo(int a) {
std::cout << "foo: running fact from simple_ex" <<std::endl;
return 1;
}
Die::Die(){}
Die::Die(int a){myVar = a;}
Die::~Die(){}
Die* Die::getDie(int a) {
return new Die (a);
}

我的.i文件:

%module example
%{
#include "example.h"
%}
%include "example.h"

我的binding.gyp文件:

{
"targets": [
{
"target_name": "example",
"sources": ["example.cpp", "example_wrap.cxx" ]
}
]
}

我遵循了swig文档中的所有命令。

我跑了:

sudo apt-get install libv8-dev
sudo apt-get install libjavascriptcoregtk-1.0-dev
swig -c++ -javascript -node example.i
node-gyp configure build

在我运行最后的命令后,我得到了各种各样的错误:

error: ‘NewSymbol’ is not a member of ‘v8::String’

还有更多。。任何帮助都可以。

谢谢!

我自己尝试过这个例子来学习这个接口
为了帮助其他可能偶然发现这一点的人,这里有一个如何工作的例子用swig和js。

首先,我们使用swig正在学习的基于对象的方法编写C++类及其逻辑

#pragma once
class Die
{
public:
Die(int a);
~Die();
int foo(int a);
int myVar;
};
extern "C" 
{
Die* getDie(int a);
}

有趣的是,我们并不总是创建一个新实例但我们使用一个外部函数向我们提供一个指向类的指针,然后该指针可以用于在我们的Javascript中导入它。这就是swig的真正意义。

以下是实现:

#include <iostream>
#include "example.h"
int Die::foo(int a) 
{
std::cout << "foo: running fact from simple_ex" << std::endl;
return 1;
}
Die::Die(int a)
{
myVar = a;
}
Die::~Die()
{
}
extern "C" 
{
Die* getDie(int a) 
{
return new Die(a);
}
}

这里还有一个函数,用于获取所述指针封装在extern C中这就是我们将它与其他类实现分离的方式,也为编译器提供了一些帮助。

swig接口与问题中的相同。它用于生成swig制作的包装文件,为我们提供Javascript和我们的C++库之间的实现接口

%module example
%{
#include "example.h"
%}
%include "example.h"

这将在终端中使用以下语句为我们创建包装文件:

swig -c++ -javascript -node example.i

现在我们需要一些Javascript工具来构建这个:

您需要安装NodeJ和NPM才能使用以下内容。

首先我们需要一个package.json文件:

{
"name": "SwigJS",
"version": "0.0.1",
"scripts": {
"start": "node index.js",
"install": "node-gyp clean configure build"

},
"dependencies": {
"nan": "^2.16.0",
"node-gyp": "^9.0.0"
}
}

这对于让构建程序了解有关包及其依赖项的一些信息非常重要。

之后,我们创建一个名为";binding.gyp";

{
"targets": [
{
"target_name": "SwigJS",
"sources": [ "example_wrap.cxx", "example.cpp" ],
"include_dirs" : [ "<!(node -e "require('nan')")" ]
}
]
}

这为我们的buildtarget和nan提供了信息。

为了实现这一点,我们现在需要创建.node文件。这可以通过使用:

node-gyp configure
node-gyp build

或使用:

npm i

两者的作用几乎和我想象的一样。(如果我错了,请纠正我)

最后我们实现了我们的Javascript,并使用了那里的库。还有一些技巧可以让顶部的路径消失,这样您可以只写require("modulname"),但对于这个例子来说,这实际上太多了。

const Swigjs = require("./build/Release/SwigJS.node");
console.log("exports :", Swigjs); //show exports to see if we have a working library
die = Swigjs.getDie(5); //get the Class pointer
console.log("foo:" + die.foo(5)); //call a function from the class

我希望这有助于清楚地了解swig和js是如何协同工作的