python打包dll被c调用,从Python调用c ++ dll

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

LONG CommOpen(BYTE port, LONG baud_rate);

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

import ctypes

lib = ctypes.WinDLL('C:\Users\toto\FIProtocol.dll')

prototype = WINFUNCTYPE(c_long, c_byte, c_long)

testPt = ctypes.WINFUNCTYPE (prototype)

testApi = testPt (("?CommOpen@CFIPcmd@@QAEJEJ@Z", lib))

Until there it seems to work but then I would like to call the in Python the equivalent in C++ of

Long l= CommOpen(5 ,115200);

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 than WinDLL because the function used the default cdecl calling convention.

Use getattr to be able to specify the mangled name.

It always pays to specify argtypes and restype 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值