pse*_*udo 2 c++ python tuples python-embedding pyobject
我有一个A像这样的python类.
class A:
def __init__(self, name):
self.name = name
def print_lastname(self, lastname):
print(lastname)
Run Code Online (Sandbox Code Playgroud)
我必须像这样调用这个代码.
import B
a = B.A("hello")
a.print_lastname("John")
Run Code Online (Sandbox Code Playgroud)
目前,我需要A从我的C++代码中使用这个类.我到目前为止.
Py_Initialize();
string hello = "hello";
PyObject *module, *attr, *arg;
module = PyObject_ImportModule("B"); // import B
attr = PyObject_GetAttrString(module, "A"); // get A from B
arg = PyString_FromString(hello.c_str());
instance = PyInstance_New(attr, arg, NULL); // trying to get instance of A with parameter "hello"
Py_Finalize();
Run Code Online (Sandbox Code Playgroud)
但我收到了错误
异常TypeError:来自'/usr/lib64/python2.7/threading.pyc'的模块'threading'中的'参数列表必须是元组'
如何从C import语句到a.print_name("John")C++实现?任何帮助表示赞赏.
我将略微重写Python类,只是它使用参数和成员变量.
# B.py - test module
class A:
def __init__(self, name):
self.name = name
def print_message(self, message):
print message + ' ' + self.name
Run Code Online (Sandbox Code Playgroud)
至于C++部分,几乎所有东西看起来都没问题.你得到的错误是因为参数PyInstance_New应该是一个元组.调用函数或方法有多种方法.以下是使用其中一个的完整示例:
// test.c - test embedding.
void error_abort(void)
{
PyErr_Print();
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
PyObject* temp, * args, * attr, * instance;
Py_Initialize();
if (!(temp = PyString_FromString("John")))
error_abort();
if (!(args = PyTuple_Pack(1, temp)))
error_abort();
Py_DECREF(temp);
if (!(temp = PyImport_ImportModule("B")))
error_abort();
if (!(attr = PyObject_GetAttrString(temp, "A")))
error_abort();
Py_DECREF(temp);
if (!(instance = PyInstance_New(attr, args, NULL)))
error_abort();
if (!PyObject_CallMethod(instance, "print_message", "s", "Hello"))
error_abort();
Py_DECREF(args);
Py_DECREF(attr);
Py_DECREF(instance);
Py_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Python纯嵌入.
| 归档时间: |
|
| 查看次数: |
558 次 |
| 最近记录: |