我现在将一些函数包装在 C++ dll 中,其原始 .h 和 .cpp 文件不可访问。学习了ctypes的教程后,我还有一些疑问。让我给你举个例子: 这是dll函数的描述文件,只说了函数名、作用和参数:
#initialize network:
BOOL InitNetwork(char LocalIP[],char ServerIP[],int LocalDeviceID)
#judging if the server is online after network initialization:
BOOL GetOnlineStatus()
#get song name:
char* GetMusicSongName(int DirIndex,int SongIndex)
#making the device playing music:
int PlayServerMusic(int DirIndex,int MusicIndex,int DeviceCout,PUINT lpDeviceID,int UseListIndex,int UserMusicIndex,UINT TaskCode)
为了用 Python 包装这些函数,我要做的是:
import ctypes
import os
#load dll
cppdll = ctypes.WinDLL("C:\\VS_projects\\MusicWebService\\MusicWebService\\NetServerInterface.dll")
#wrap dll functions:
#initialize network:
def InitNetwork(LocalIP, ServerIP, LocalDeviceID):
return cppdll.InitNetwork(LocalIP, ServerIP, LocalDeviceID)
InitNetwork.argtypes = [c_char, c_char, c_int]
#judging if the server is online after network initialization:
def GetOnlineStatus():
return cppdll.GetOnlineStatus()
#get song name:
def GetMusicSongName(DirIndex, SongIndex):
return cppdll.GetMusicSongName(DirIndex, SongIndex)
GetMusicSongName.argtypes = [c_int, c_int]
#making the device playing music:
def PlayServerMusic(DirIndex, MusicIndex, DeviceCout, lpDeviceID, UseListIndex, UserMusicIndex, TaskCode):
return cppdll.PlayServerMusic(DirIndex, MusicIndex, DeviceCout, lpDeviceID, UseListIndex, UserMusicIndex, TaskCode)
当我在 VS2015 python interactice 窗口中键入并定义第一个函数(在导入包和加载 dll 之后)时,它给了我一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c_char' is not defined
我需要指定输入参数的类型吗?如果是这样,该怎么做?我无法识别第四个函数中的某些参数类型,例如 PUINT lpDeviceID
和 UINT TaskCode
。如何指定它们?
此外,我需要指定函数返回值的类型吗?如果是这样,如何指定它们?
有人可以给我上面示例的正确包装代码吗?感谢您的关注!
最佳答案
您的问题是您的 namespace 不正确。它的
cppdll.InitNetwork.argtypes = [ctypes.c_char, ctypes.c_char, ctypes.c_int]
您可以将需要的ctypes数据直接导入到模块中。由于 ctypes
为您创建函数包装器,您实际上并不需要自己的 def
来做同样的事情。您可以使用 cppdll.Whatever
调用它们,但如果您喜欢在命名空间级别使用这些函数,您可以只为它们创建变量。
from ctypes import WinDLL, c_char, c_int
import os
#load dll
cppdll = ctypes.WinDLL("C:\\VS_projects\\MusicWebService\\MusicWebService\\NetServerInterface.dll")
#initialize network:
InitNetwork = cppdll.InitNetwork
InitNetwork.argtypes = [c_char, c_char, c_int]
#judging if the server is online after network initialization:
GetOnlineStatus = cppdll.GetOnlineStatus
#get song name:
GetMusicSongName = cppdll.GetMusicSongName
GetMusicSongName.argtypes = [c_int, c_int]
#making the device playing music:
PlayServerMusic = cppdll.PlayServerMusic
PlayServerMusic = ...
关于python - 使用 ctypes 包装 DLL 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054334/