问题描述
我必须使用一个C ++ dll使用MFC,我想从python调用它。
此dll在.h文件中包含此标题
然后我在自由软件dllexp中看到我的函数被调用了?CommOpen @ CFIPcmd @@ QAEJEJ @ Z在二进制文件中,所以没有报告错误当我在python做的时候
直到它似乎工作,但是我想在Python中调用
没有找到知道如何继续。
给出问题中提供的信息,解决方案是: / p>
import ctypes
lib = ctypes.CDLL(r'C:\Users\toto\\ \\ FIProtocol.dll')
CommOpen = getattr(lib,?CommOpen @ CFIPcmd @@ QAEJEJ @ Z)
CommOpen.argtypes = [c_byte,c_long]
CommOpen.restype = c_long
现在可以调用:
l = CommOpen(5,115200)
:
- 使用
CDLL
而不是WinDLL
因为该函数使用默认的cdecl
调用约定。 - 使用
getattr $ c 必须指定
才能指定该名称。
- 。
一个更大的问题。上面写的是基于你的函数是一个非成员函数。这是一个合理的假设,因为 ctypes
要求函数为非成员或静态。
当我把你的托管功能名称放在一个demanger中(例如)看起来函数其实是:
public:long __thiscall CFIPcmd :: CommOpen(unsigned char,long)
这是一个C ++对象的成员函数。无法从 ctypes
访问。您将需要创建一个简单的C样式包装器,或者找到一种不同的interop方法。
I must used a C++ dll using MFC and I would like to call it from python.This dll contains this header in the .h file
Then I see in the free software dllexp that my function is called ?CommOpen@CFIPcmd@@QAEJEJ@Z in the binary file so no error is reported when I do in python
Until there it seems to work but then I would like to call the in Python the equivalent in C++ of
But I Didn't find know how to proceed.Any help would be really appreciated!!
Given the information presented in the question, the solution is:
import ctypes
lib = ctypes.CDLL(r'C:\Users\toto\FIProtocol.dll')
CommOpen = getattr(lib, "?CommOpen@CFIPcmd@@QAEJEJ@Z")
CommOpen.argtypes = [c_byte, c_long]
CommOpen.restype = c_long
And now it is ready to call:
l = CommOpen(5 ,115200)
Some notes:
- Use
CDLL
rather thanWinDLL
because the function used the defaultcdecl
calling convention. - Use
getattr
to be able to specify the mangled name. - It always pays to specify
argtypes
andrestype
explicitly.
However, it transpires that you have a much greater problem. The above was written on the basis that your function is a non-member function. Which is a reasonable assumption given that ctypes
requires functions to be either non-member, or static.
However, when I put your managed function name into a demanger (for instance http://pear.warosu.org/c++filtjs/) it seems that the function is in fact:
public: long __thiscall CFIPcmd::CommOpen(unsigned char,long)
That is a member function of a C++ object. That cannot be accessed from ctypes
. You'll need to create a plain C style wrapper, or find a different method of interop.
这篇关于从Python调用c ++ dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!