2016-08-18 29 views
0

我正在寫一個正被使用,如下一個Python腳本調用的DLL:ctypes的

//sample.h 
#include<stdio.h> 
typedef struct _data 
{ 
char * name; 
}data,*xdata; 
__declspec(dllexport) void getinfo(data xdata,HRESULT *error); 


//sample.c 
#include<stdio.h> 
#include"sample.h" 
void get(data xdata,HRESULT *error) 
{ 
    //something is being done here 
} 

現在,用於調用上述功能的Python腳本被如下所示:

//sample.py 
import ctypes 
import sys 
from ctypes import * 
mydll=CDLL('sample.dll') 
class data(Structure): 
    _fields_ = [('name',c_char_p)] 

def get(): 
    xdata=data() 
    error=HRESULT() 
    mydll=CDLL('sample.dll') 
    mydll.get.argtypes=[POINTER(data),POINTER(HRESULT)] 
    mydll.get.restype = None 
    mydll.get(xdata,error) 
    return xdata.value,error.value 

xdata=get() 
error=get() 
print "information=",xdata.value 
print "error=", error.value 

但是我運行python腳本後得到的錯誤是:

Debug Assertion Failed! 
Program:C:\Python27\pythonw.exe 
File:minkernel\crts\ucrt\src\appcrt\stdio\fgets.cpp 
Expression:stream.valid() 

任何人可以幫助我在SOLV問題是什麼?而我寫的python腳本,是寫它的正確方法嗎?

+0

的錯誤指示使用不創建控制檯的'pythonw.exe'。 'fgets()'沒有顯示在你的代碼中,但是如果它試圖從'stdin'讀取這個沒有控制檯的無效流。 –

+0

我注意到的另一件事是'data xdata'是'getinfo'的一個參數。這種類型在Python中不是'POINTER(data)',而只是'data'。 –

+0

你也從Python get()中返回了兩個值,所以'xdata,error = get()'而不是'xdata = get()'和'error = get()'。 –

回答

0

根據我的意見,我懷疑fgets()的錯誤在代碼中未顯示,但是在顯示的Python和C代碼中也存在問題。下面是我使用的DLL源,確保指針傳遞到數據結構:

typedef long HRESULT; 

typedef struct _data { 
    char * name; 
} data; 

// Make sure to pass a pointer to data. 
__declspec(dllexport) void getinfo(data* pdata, HRESULT *error) 
{ 
    pdata->name = "Mark"; 
    *error = 0; 
} 

而這裏的修正Python代碼:

from ctypes import * 

class data(Structure): 
    _fields_ = [('name',c_char_p)] 

def get(): 
    xdata=data() 
    error=HRESULT() 
    mydll=CDLL('sample.dll') 
    mydll.getinfo.argtypes=[POINTER(data),POINTER(HRESULT)] 
    mydll.getinfo.restype = None 
    mydll.getinfo(xdata,error) 
    return xdata,error 

# Correction in next two lines 
xdata,error = get() 
print "information =",xdata.name 
print "error =", error.value 

輸出:

information = Mark 
error = 0