Reputation: 23
I'm trying to porting some C dll(FANUC FOCAS Library - for CNC) code via Python using ctypes, so I wrote porting code. (as belows), but get a very strange result when loading the DLL and calling the function. In my case, I don't understand using handler in python.
I would like to apply the following c code in python.
Declaration(for c)
#include "fwlib64.h"
FWLIBAPI short WINAPI cnc_allclibhndl3(const char *ipaddr,unsigned short port,
long timeout, unsigned short *FlibHndl);
Example Code(in focas library manual for c)
#include "fwlib64.h"
void example( void )
{
unsigned short h;
short ret;
ODBST buf;
ret = cnc_allclibhndl3( "192.168.0.100", 8193, 1, &h ) ;
//
if ( !ret ) {
cnc_statinfo( h, &buf ) ;
cnc_freelibhndl( h ) ;
} else {
printf( "ERROR!(%d)\n", ret ) ;
}
}
Testfocas.py
from ctypes import *
mylib = cdll.LoadLibrary('./Fwlib64.dll')
class ODBSYS(Structure):
pass
_fields_ =[
("dummy", c_ushort),
("max_axis", c_char*2),
("cnc_type", c_char*2),
("mt_type",c_char*2),
("series",c_char*4),
("version",c_char*4),
("axes",c_char*2),]
h=c_ushort()
pt=pointer(h)
ret=c_short()
buf=ODBSYS()
ret=mylib.cnc_allclibhndl3('192.168.0.100',8193,1,pt)
mylib.cnc_statinfo(h,buf)
mylib.cnc_freelibhndl(h)
I want the function to return 0 or -16 but, in my case the function return is
cnc_allclibhndl3 = 65520 (i guess open port)
cnc_statinfo = -8
cnc_freelibhndl -8
Return Status of Data Window Functions
EW_OK(0) Normal termination
EW_SOCKET(-16) Socket communication error Check the power supply of CNC, Ethernet I/F board, Ethernet connection cable.
EW_HANDLE(-8) Allocation of handle number is failed.
I do not know what I was wrong with.
Upvotes: 2
Views: 2089
Reputation: 177471
CDLL
is for __cdecl
calling convention. cdll
is not recommended for use because it is a shared instance across modules.
WINAPI
is defined as __stdcall
, so use WinDLL
:
mylib = WinDLL.LoadLibrary('./Fwlib64.dll')
Next, define argtypes
and restype
for your argument and result types for your function:
mylib.cnc_allclibhndl3.argtypes = c_char_p,c_ushort,c_long,POINTER(c_ushort)
mylib.cnc_allclibhndl3.restype = c_short
Finally, pass the output parameter by reference. It is more efficient than creating a pointer
:
h = c_ushort()
ret = mylib.cnc_allclibhndl3('192.168.0.100',8193,1,byref(h))
Prototypes for cnc_statinfo
and cnc_freelibhndl
were not provided. Define argtypes
and restype
for them as well.
Upvotes: 3