处理程序问题在Python中应用cdll

时间:2017-01-16 11:55:12

标签: python c dll ctypes

我试图通过Python使用ctypes移植一些C dll(FANUC FOCAS库 - 用于CNC)代码,因此我编写了移植代码。 (如下所示),但在加载DLL并调用函数时得到一个非常奇怪的结果。就我而言,我不理解在python中使用handler。

我想在python中应用以下c代码。

声明(适用于c)

#include "fwlib64.h"
FWLIBAPI short WINAPI cnc_allclibhndl3(const char *ipaddr,unsigned short port,
long timeout, unsigned short *FlibHndl);

示例代码(在c的focas库手册中)

#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)

我希望函数返回0或-16,但在我的情况下,函数返回是

  

cnc_allclibhndl3 = 65520(我想打开端口)

     

cnc_statinfo = -8

     

cnc_freelibhndl -8

返回数据窗口函数的状态

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.  

我不知道我的错误。

1 个答案:

答案 0 :(得分:1)

CDLL用于__cdecl调用约定。建议不要使用cdll,因为它是跨模块的共享实例。

WINAPI定义为__stdcall,因此请使用WinDLL

mylib = WinDLL.LoadLibrary('./Fwlib64.dll')

接下来,为您的函数的参数和结果类型定义argtypesrestype

mylib.cnc_allclibhndl3.argtypes = c_char_p,c_ushort,c_long,POINTER(c_ushort)
mylib.cnc_allclibhndl3.restype = c_short

最后,通过引用传递输出参数。它比创建pointer

更有效
h = c_ushort()
ret = mylib.cnc_allclibhndl3('192.168.0.100',8193,1,byref(h))

未提供cnc_statinfocnc_freelibhndl的原型。为他们定义argtypesrestype