我是一名初学者Python程序员,正在将一些Python代码嵌入到C++ DLL中。无法使PyObject_CallMethod工作,每次调用Python 3.6类方法时都会返回Null。创建了一个小示例来说明这个问题,请查看代码中的注释。希望能得到一些关于我做错了什么的指导。
#include "stdafx.h"
using namespace std;
int TestBasicStats()
{
_putenv_s("PYTHONPATH", ".");
Py_Initialize();
PyObject* module = PyImport_ImportModule("BasicStats");
assert(module != NULL); // Returned non-null object
PyObject* MyPyClass = PyObject_GetAttrString(module, "BasicStats");
assert(MyPyClass != NULL);// Returned non-null object
PyObject* myClassInstance = PyInstanceMethod_New(MyPyClass);
assert(myClassInstance != NULL);// Returned non-null object
PyObject* result = PyObject_CallMethod(myClassInstance, "AddItem", "(i)", 1);
assert(result != NULL); // Failed - returned NULL
result = PyObject_CallMethod(myClassInstance, "AddItem", "(i)", 2);
assert(result != NULL); // Failed - returned NULL
result = PyObject_CallMethod(myClassInstance, "get_Max", NULL);
assert(result != NULL); // Failed - returned NULL
printf("Min = %ld\n", PyLong_AsLong(result));
printf("Min = %f\n", PyFloat_AsDouble(result));
Py_Finalize();
return 0;
}
int main()
{
TestBasicStats();
return 0;
}
Python类的名称如下所示:
class BasicStats:
def __init__(self):
self._m_min = self._m_max = self._m_sum = self._m_sumSqr = 0
self._m_count = 0
self.Reset()
def Reset(self):
self._m_min = float("inf")
self._m_max = float("-inf")
self._m_sum = self._m_sumSqr = 0
self._m_count = 0
def AddItem(self, value):
self._m_count += 1
if self._m_max < value:
self._m_max = value
def get_Max(self):
return self._m_max
Max = property(fget=get_Max)
PyInstanceMethod_New
创建一个函数,这就解释了为什么它不起作用,因为它实际上并没有创建一个实例。 - user253751