无法在python中加载C ++ DLL

时间:2015-02-03 16:34:28

标签: python dll ctypes

我有 C ++ dll ,我试图在 Python 中使用,

>>> from ctypes import *
>>> mydll = cdll.LoadLibrary("C:\\TestDll.dll")

直到现在没有错误,系统似乎正在做我想要的,但当我尝试访问mydll时,Python IDLE中的Intellisence显示以下内容,

enter image description here

从上面的图片中可以清楚地看到,intellisence并没有显示dll的任何可用功能,但当我用dumpbin /EXPORTS TestDll.dll检查相同的TestDll.dll时它有45个功能,但这些函数都不适用于python。

enter image description here

请注意:关于此主题有几个问题,我尝试了以下建议但没有用,

现在我的问题是如何加载所有可用的功能(如dumpbin所示)?

修改1

根据eryksun建议,我能够取得一些进展。 TestDll.dll附带了一个头文件TestDll.h(我的错误,我之前错过了这个文件),从中可以看到可用的导出函数。

TestDll.h:

_stdcall Function1 (const char* prtFileString, cont char* prtDescrip, struct FileParams* ptrParsms);

struct FileParams
{
  float val1;
  void* pMarker;
};

现在我尝试了以下内容,

>>> mydll = CDLL("c:\\TestDll.dll")
>>> Function1 = mydll.Function1
>>> Function1.restype = c_int

直到现在它还不错,但是当我尝试定义 argTypes 时,不确定如何为结构做到这一点?

>>> Function1.argtypes = (c_char_c, c_char_c, ???)

非常感谢任何建议。

1 个答案:

答案 0 :(得分:2)

根据您的标题,这是一个虚拟C文件(适用于Windows),可用于测试ctypes包装器。你提到了C ++,但是这个例子是一个C接口,这是一件好事,因为ctypes适用于C函数而不是C ++。

x.c

#include <stdio.h>

struct FileParams
{
  float val1;
  void* pMarker;
};

__declspec(dllexport) _stdcall Function1 (const char* prtFileString, const char* prtDescrip, struct FileParams* ptrParsms)
{
    printf("%s\n%s\n%f %p\n",prtFileString,prtDescrip,ptrParsms->val1,ptrParsms->pMarker);
}

这是ctypes包装器。请注意ctypes不检查DLL并自动加载所有函数。您必须自己声明函数,参数和返回值。有关Structure语法,请参阅ctypes:structures and unions

另请注意,对于具有_stdcall个函数的DLL,请使用WinDLL而不是CDLL

x.py

#!python3
import ctypes

class FileParams(ctypes.Structure):
    _fields_ = [('val1',ctypes.c_float),
                ('pMarker',ctypes.c_void_p)]

    x = ctypes.WinDLL('x')
    x.Function1.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(FileParams)]
    x.Function1.restype = ctypes.c_int

    fp = FileParams(1.234,None)
    x.Function1(b'abc',b'def',ctypes.byref(fp))

输出:

abc
def
1.234000 0000000000000000