我知道这是一个老问题,但这里是使用SWIG的解决办法。
foo.h:
#pragma once
#include <string>
struct Foo{
Foo();
Foo(std::string const& s);
void doSomething();
std::string m_string;
};
foo.cpp:
#include "foo.h"
#include <iostream>
Foo::Foo() {}
Foo::Foo(std::string const& s) : m_string(s) {}
void Foo::doSomething() {
std::cout << "Foo:" << m_string << std::endl;
}
foo.i:
%module module
%{
#include "foo.h"
%}
%include "std_string.i"
%include "foo.h"
Generate the usual SWIG wrapper together with a runtime
swig -python -c++ -Wall foo.i
swig -python -c++ -Wall -external-runtime runtime.h
制作包含<代码>结构的SWIG模块 Foo:
g++ -fPIC -Wall -Wextra -shared -o _module.so foo_wrap.cxx foo.cpp -I/usr/include/python2.7 -lpython2.7
如果你想在多个单元之间分享类型信息,可添加一个论点:-DSWIG_TYPE_TABLE=SomeName
。
现在这里是“C++”的例子。 Foo 传给口译员
#include "foo.h"
#include <Python.h>
#include "runtime.h"
int main(int argc, char **argv) {
Py_Initialize();
PyObject* syspath = PySys_GetObject((char*)"path");
PyObject* pName = PyString_FromString((char*) ".");
int err = PyList_Insert(syspath, 0, pName);
Py_DECREF(pName);
err = PySys_SetObject((char*) "path", syspath);
PyObject *main, *module, *pInstance, *run, *setup;
try {
main = PyImport_ImportModule("__main__");
err = PyRun_SimpleString(
"a_foo = None
"
"
"
"def setup(a_foo_from_cxx):
"
" print setup called with , a_foo_from_cxx
"
" global a_foo
"
" a_foo = a_foo_from_cxx
"
"
"
"def run():
"
" a_foo.doSomething()
"
"
"
"print main module loaded
");
// Load Python module
module = PyImport_ImportModule("module");
swig_type_info *pTypeInfo = nullptr;
pTypeInfo = SWIG_TypeQuery("Foo *");
Foo* pFoo = new Foo("Hello");
int owned = 1;
pInstance =
SWIG_NewPointerObj(reinterpret_cast<void*>(pFoo), pTypeInfo, owned);
setup = PyObject_GetAttrString(main, "setup");
PyObject* result = PyObject_CallFunctionObjArgs(setup, pInstance, NULL);
Py_DECREF(result);
run = PyObject_GetAttrString(main, "run");
result = PyObject_CallFunctionObjArgs(run, NULL);
Py_DECREF(result);
}
catch (...) {
PyErr_Print();
}
Py_DECREF(run);
Py_DECREF(setup);
Py_DECREF(pInstance);
Py_DECREF(module);
Py_DECREF(main);
Py_Finalize();
return 0;
}
以上内容可通过:
g++ -Wall -Wextra -I/usr/include/python2.7 main.cpp foo.cpp -o main -lpython2.7