python loadlibrary_Python ctypes cdll.LoadLibrary,实例化一个对象,执...

本文详细介绍了如何在Python中通过ctypes库加载C动态链接库,并正确设置argtypes和restype以避免未定义行为。通过示例展示了创建C++类的Python绑定,包括实例化、调用成员函数以及内存管理。同时,强调了在64位系统中不指定argtypes和restype可能导致的数据截断问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值