我正在编写一个使用python脚本调用的DLL,如下所示:
//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()
有人可以帮我解决问题吗?我写过的python脚本是不是写它的正确方法?
答案 0 :(得分: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