问题: 当我尝试运行以下python代码时,我收到此错误:
文件" pydog.py",第21行,在 srclib.log_dog.argtypes = [pug]
TypeError: argtypes 中的第1项没有from_param方法
pydog.py:
import ctypes
from ctypes import *
srclib = ctypes.CDLL('/path/DogHouse.so')
class dog(Structure):
_fields_ = [
("name", ctypes.c_char*10),
("color", ctypes.c_char*10)]
pug = dog("doug", "white")
#- Not sure if I need to define arg and res types -#
srclib.log_dog.argtypes = [pug]
#srclib.log_dog.restype =
srclib.log_dog(pug)
DogHouse.h:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* opaque handle */
typedef struct __dog_file dogfile;
/* Input data structure */
typedef struct __dog_input{
const char *name;
const char *color;
}dog_input;
/*Logs the dog_input data into the dog_file struct */
dog_file *log_dog(const dog_input *data);
DogHouse.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "DogHouse.h"
struct __dog_file{
const char *name;
const char *color;
};
dog_file *log_dog(const dog_input *data){
dog_file *df;
df->name = data->name;
df->color = data->color;
return df;
}
int main(int argc, char **argv){
}
我尝试找到&#34; from_param&#34;的语法,但我无法找到具体的内容(我不确定它是ctypes特定的,还是python库的标准
这是我关于SO的第一个问题,所以如果我需要改变任何事情/请更清楚地告诉我!在此先感谢您的帮助。
答案 0 :(得分:1)
argtypes
中的值应为类型。 pug
是一个实例。给出的代码不会编译,但以下是我提出的:
<强> pydog.py 强>
import ctypes
srclib = ctypes.CDLL('DogHouse')
# An opaque class
class dog_file(ctypes.Structure):
pass
# c_char_p should be used for "const char *"
class dog_input(ctypes.Structure):
_fields_ = [
("name", ctypes.c_char_p),
("color", ctypes.c_char_p)]
srclib.log_dog.argtypes = [ctypes.POINTER(dog_input)] # pointer type
srclib.log_dog.restype = ctypes.POINTER(dog_file) # pointer type to opaque class
# bytes strings used for const char* (Python 3 syntax)
# create instance and pass it to function
pug = dog_input(b'doug',b'white')
print(srclib.log_dog(pug))
<强> DogHouse.h 强>
/* opaque handle */
typedef struct dog_file dog_file;
/* Input data structure */
typedef struct dog_input
{
const char* name;
const char* color;
} dog_input;
/*Logs the dog_input data into the dog_file struct */
__declspec(dllexport)
dog_file* log_dog(const dog_input* data);
<强> DogHouse.c 强>
#include <stdlib.h>
#include "DogHouse.h"
typedef struct dog_file
{
const char* name;
const char* color;
} dog_file;
dog_file* log_dog(const dog_input* data)
{
dog_file* df = malloc(sizeof(dog_file));
df->name = data->name;
df->color = data->color;
return df;
}
请注意,在函数实现中,原始函数返回了一个局部变量。这个版本mallocs内存,但你需要导出另一个函数来释放它或者有内存泄漏。
输出(不透明指针实例)
<__main__.LP_dog_file object at 0x00000000030040C8>