python好还是c+-python与c ++使用ctypes

1586010002-jmsa.png

As I'm still new to this, I'm facing some problems, here's my C++ code:

#include

#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT PyObject *Add(PyObject *pSelf, PyObject *pArgs)

{

int s,d;

if(!PyArg_ParseTuple(pArgs, "ii" , &s, &d))

{

PyErr_SetString(PyExc_TypeError,

"Add() invalid parameter");

return NULL;

}

return Py_BuildValue("i", s + d);

}

And the Python code:

import ctypes

MyDll = ctypes.cdll.LoadLibrary(r"PyToCppTest.dll")

jj = MyDll.Add(1,2)

I get an error when I run the above Python code:

OSError: exception: access violation reading 0x000000000000000A

I want to pass the data, without converting it, from Python to C++, then convert it inside C++.

解决方案

There are a few things that are wrong with your code. First and foremost, the proper include is:

#include

Note the capital P. You're probably on Windows, but this wouldn't work on Linux without the capital P.

Also, I don't see the point of the *pSelf pointer in your function declaration, you should get rid of it:

PyObject *Add(PyObject *pArgs)

Now, your main problem is this:

MyDll.Add(1,2)

...does not call MyDll.Add with a tuple. It calls it with two integer arguments, 1 and 2. If you want to pass a tuple, you'd do:

MyDll.Add((1,2))

However, Python's ctypes won't know what to do with this (it normally accepts integer arguments), so you'll need to tell it that Add actually wants a tuple, and returns a Python object:

import ctypes

MyDll = ctypes.cdll.LoadLibrary("PyToCppTest.dll")

MyCFunc = ctypes.PYFUNCTYPE(

ctypes.py_object, # return val: a python object

ctypes.py_object # argument 1: a tuple

)

MyFunc = MyCFunc(('Add', MyDll))

jj = MyFunc((1,2))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值