使用 HRESULT(python) 的 ctypes
Posted
技术标签:
【中文标题】使用 HRESULT(python) 的 ctypes【英文标题】:ctypes using HRESULT(python) 【发布时间】:2016-08-18 13:02:59 【问题描述】:我正在编写一个 DLL,该 DLL 使用如下 Python 脚本调用:
//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脚本,是不是正确的写法?
【问题讨论】:
该错误表明使用pythonw.exe
不会创建控制台。 fgets()
未显示在您的代码中,但如果它试图从 stdin
读取,那将是一个没有控制台的无效流。
我注意到的另一件事是data xdata
是getinfo
的参数。该类型在 Python 中不是 POINTER(data)
,而只是 data
。
您还从 Python get()
返回了两个值,所以 xdata,error = get()
而不是 xdata=get()
和 error=get()
。
【参考方案1】:
根据我的 cmets,我怀疑 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
【讨论】:
以上是关于使用 HRESULT(python) 的 ctypes的主要内容,如果未能解决你的问题,请参考以下文章