ctypes using HRESULT(python)

ctypes using HRESULT(python)

本文关键字:python HRESULT using ctypes      更新时间:2023-10-16

我正在编写一个使用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:Python27pythonw.exe
File:minkernelcrtsucrtsrcappcrtstdiofgets.cpp
Expression:stream.valid()
谁能帮我解决这个问题?我写的python脚本,这样写对吗?

根据我的评论,我怀疑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