问题:当我尝试运行以下 python 代码时,出现此错误:
File "pydog.py", line 21, in
srclib.log_dog.argtypes = [pug]
TypeError: item 1 in argtypes has no from_param method
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)
Run Code Online (Sandbox Code Playgroud)
狗屋.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);
Run Code Online (Sandbox Code Playgroud)
狗屋.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){
}
Run Code Online (Sandbox Code Playgroud)
我尝试查找“from_param”的语法,但找不到具体需要的内容(我不确定它是 ctypes 特定的还是 python 库的标准。
这是我的第一个问题,所以如果我需要更改任何内容/更清楚,请告诉我!预先感谢您的任何帮助。
中的值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))
Run Code Online (Sandbox Code Playgroud)
狗屋.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);
Run Code Online (Sandbox Code Playgroud)
狗屋.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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,在函数实现中,原始函数返回一个局部变量。此版本会分配内存,但您需要导出另一个函数来释放它,否则会出现内存泄漏。
输出(不透明指针实例)
<__main__.LP_dog_file object at 0x00000000030040C8>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4477 次 |
| 最近记录: |