简体   繁体   中英

Calling Windows 64 Dll with Python Ctypes

I'm trying to call a SimpleMotionv2 library from python using ctypes, it appears to make the call, but it always returns -1 when I feed it a valid com port.

I've built the DLL and the function I'm trying to call seems exported properly:

DLL Export Viewer Output

Somehow I'm passing the COM port number incorrectly? I'm on windows and its COM5...

The function I'm calling is smOpenBus() and is listed here:

smbus smOpenBus( const char * devicename )
{
    int handle;

    //true on first call
    if(smInitialized==smfalse)
        smBusesInit();

    //find free handle
    for(handle=0;handle<SM_MAX_BUSES;handle++)
    {
        if(smBus[handle].opened==smfalse) break;//choose this
    }
    //all handles in use
    if(handle>=SM_MAX_BUSES) return -1;

    //open bus device
    smBus[handle].bdHandle=smBDOpen(devicename);
    if(smBus[handle].bdHandle==-1) return -1;

    //success
    strncpy( smBus[handle].busDeviceName, devicename, SM_BUSDEVICENAME_LEN );
    smBus[handle].busDeviceName[SM_BUSDEVICENAME_LEN-1]=0;//null terminate string
    smBus[handle].opened=smtrue;
    return handle;
}

And my Python code is:

import ctypes as ct

dll = ct.CDLL(r'./SMv2_x64.dll')

dll.smOpenBus.argtypes = ct.c_char_p,
dll.smOpenBus.restype = ct.c_long

ret_val = dll.smOpenBus(b'COM24')
print(ret_val)

What on Earth am I doing wrong?

I've tried making the ptr of type c_wchar_p and c_char_p, adding NULL terminators and string and not... I expect to get a COM port handle return and I get -1.

It’s argtypes (plural) and is a tuple. c_char_p is appropriate for C char* :

dll.smOpenBus.argtypes = ct.c_char_p, # comma makes a 1-tuple

Then pass a byte string:

ret_val = dll.smOpenBus(b'COM5')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM