python - 使用来自 C++、PyObject 的参数创建 Python 构造函数

标签 python c++ tuples python-embedding pyobject

我有一个像这样的 python 类 A

class A: 
   def __init__(self, name): 
       self.name = name

   def print_lastname(self, lastname): 
       print(lastname)

我必须这样调用这段代码。

import B
a = B.A("hello")
a.print_lastname("John")

目前,我需要在我的 C++ 代码中使用这个 A 类。我已经走到这一步了。

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(); 

但是我得到了错误

Exception TypeError: 'argument list must be tuple' in module 'threading' from '/usr/lib64/python2.7/threading.pyc'

如何从 C++ 实现从 import 语句到 a.print_name("John")? 感谢您的帮助。

最佳答案

我将稍微重写 Python 类,这样它就可以同时使用参数和成员变量。

# B.py - test module
class A:
    def __init__(self, name):
        self.name = name

    def print_message(self, message):
        print message + ' ' + self.name

至于 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;
}

有关详细信息,请参阅 Python pure-embedding .

关于python - 使用来自 C++、PyObject 的参数创建 Python 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40142379/

相关文章:

c++ - 为什么允许在派生类中调用 protected 静态方法?

c++ - 将 vector 传递给 qsort

ios - 快速打开一个元组

list - Scala 过滤元组列表

python - 如何听写文件夹?

python - 使用 python 从 Excel 工作表中提取图像

c++ - C 堆栈跟踪中缺少函数调用

python - 在带参数的函数中使用 timeit 模块

python - 检查列表中的所有元素是否唯一

c# - Tuple<List<int>, List<int>> 还是 List<Tuple<int, int>>?