Always(CORRECTLY)为C中定义的函数指定argtypes和restype,否则(C89样式)它们将默认为int(32bit),生成!!!未定义的行为!!!在64位,它可能会导致截断(这正是您正在经历的).
下面是您的代码的改编版本.
detector.cpp:
#include
#include
#include
#define C_TAG "From C"
#define PRINT_MSG_2SP(ARG0, ARG1) printf("%s - [%s] (%d) - [%s]: %s: 0x%0p
", C_TAG, __FILE__, __LINE__, __FUNCTION__, ARG0, ARG1)
using std::endl;
std::ofstream outFile;
class Detector {
public:
Detector();
void process(int *pIn, int *pOut, int n);
private:
int m_var;
};
Detector::Detector()
: m_var(0) {
outFile.open("addr_debug.txt");
outFile << "m_var init address: " << &m_var << endl;
PRINT_MSG_2SP("&m_var", &m_var);
}
void Detector::process(int *pIn, int *pOut, int n) {
outFile << "m_var process address: " << &m_var << endl;
outFile.close();
PRINT_MSG_2SP("&m_var", &m_var);
}
#define SIM_EXPORT __declspec(dllexport)
#if defined(__cplusplus)
extern "C" {
#endif
SIM_EXPORT Detector *DetectorNew() { return new Detector(); }
SIM_EXPORT void DetectorProcess(Detector *pDet, int *pIn, int *pOut, int n) {
pDet->process(pIn, pOut, n);
}
SIM_EXPORT void DetectorDelete(Detector *pDet) { delete pDet; }
#if defined(__cplusplus)
}
#endif
code.py:
import sys
from ctypes import CDLL, POINTER, \n c_int, c_void_p
import numpy as np
sim_dll = CDLL("./sim.dll")
detector_new_func = sim_dll.DetectorNew
detector_new_func.restype = c_void_p
detector_process_func = sim_dll.DetectorProcess
detector_process_func.argtypes = [c_void_p, POINTER(c_int), POINTER(c_int), c_int]
detector_delete_func = sim_dll.DetectorDelete
detector_delete_func.argtypes = [c_void_p]
class Detector():
def __init__(self):
self.obj = detector_new_func()
def process(self, pin, pout, n):
detector_process_func(self.obj, pin, pout, n)
def __del__(self):
detector_delete_func(self.obj)
def main():
detector = Detector()
n = 1024
a = np.arange(n, dtype=np.uint32)
b = np.zeros(n, dtype=np.int32)
aptr = a.ctypes.data_as(POINTER(c_int))
bptr = b.ctypes.data_as(POINTER(c_int))
detector.process(aptr, bptr, n)
if __name__ == "__main__":
print("Python {:s} on {:s}
".format(sys.version, sys.platform))
main()
笔记:
>正如我在开头所说,问题是argtypes和restype没有被指定(例如对于DetectorNew:注释detector_new_func.restype = c_void_p,你会再次遇到问题)
>问题中的代码缺少部分(#includes,imports,…),也存在一些语法错误,因此无法编译,因此不遵循[SO]: How to create a Minimal, Complete, and Verifiable example (mcve)准则.请问时确保有mcve
>你分配的对象(新的Detector())也必须被释放(否则,它会产生内存泄漏),所以我添加了一个函数(DetectorDelete – 来做),从(Python)Detector的析构函数调用
>其他(非关键)更改(标识符重命名,一点重构,打印到stdout,……)
输出:
06002