I'm now wrapping some functions in C++ dll whose original .h an .cpp file are not accessable. After learning the tutorial of ctypes, I still have the some questions. Let me show you some example: This is from the description file of the dll functions, just telling functions' names, effects and parameters:
#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)
In order to wrap these functions in Python, what I'm tring to do is this:
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)
When I type and define the first function (after importing packages and loading the dll) in the VS2015 python interactice window, it gives me an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c_char' is not defined
Do I need to specify the type of input parameters? If so, how to do this? I can't recognize the type of some parameters in the forth function such as PUINT lpDeviceID
and UINT TaskCode
. How to specify them?
Moreover, do I need to specify the functions' return value's type? If so, how to specify them?
Could somebody give me the correct wrapping code of the examples above? Thanks for your attention!
InitNetwork.argtypes = [c_char, c_char, c_int]
looks suspicious, as the original c-function accepts a pointer, not a character. Possibly you needc_void_p
instead? – Aconcagua