python创建对象调用对象的方法_在C++中创建Python对象并调用其方法

通过做一些调查,我发现可以使用下面的四个API系列来实现这一点。在PyModule_GetDict;获取属于python模块的项。*

PyDict_GetItemString;获取Python类对应的项

姓名。

PyObject_CallObject;创建Python对象。*在

PyObject_CallMethod;对象的类a方法。在

下面是我创建的示例代码,尽管它还需要改进。在// Refer to the following website for more information about embedding the

// Python code in C++.

// https://docs.python.org/2/extending/embedding.html

int main() {

PyObject *module_name, *module, *dict, *python_class, *object;

// Initializes the Python interpreter

Py_Initialize();

module_name = PyString_FromString(

"work.embedding_python_in_cpp.example.adder");

// Load the module object

module = PyImport_Import(module_name);

if (module == nullptr) {

PyErr_Print();

std::cerr << "Fails to import the module.\n";

return 1;

}

Py_DECREF(module_name);

// dict is a borrowed reference.

dict = PyModule_GetDict(module);

if (dict == nullptr) {

PyErr_Print();

std::cerr << "Fails to get the dictionary.\n";

return 1;

}

Py_DECREF(module);

// Builds the name of a callable class

python_class = PyDict_GetItemString(dict, "Adder");

if (python_class == nullptr) {

PyErr_Print();

std::cerr << "Fails to get the Python class.\n";

return 1;

}

Py_DECREF(dict);

// Creates an instance of the class

if (PyCallable_Check(python_class)) {

object = PyObject_CallObject(python_class, nullptr);

Py_DECREF(python_class);

} else {

std::cout << "Cannot instantiate the Python class" << std::endl;

Py_DECREF(python_class);

return 1;

}

int sum = 0;

int x;

for (size_t i = 0; i < 5; i++) {

x = rand() % 100;

sum += x;

PyObject *value = PyObject_CallMethod(object, "add", "(i)", x);

if (value)

Py_DECREF(value);

else

PyErr_Print();

}

PyObject_CallMethod(object, "printSum", nullptr);

std::cout << "the sum via C++ is " << sum << std::endl;

std::getchar();

Py_Finalize();

return (0);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值