我在使用Python C Binding包装器方面有一些经验,但现在给我最悲伤的功能是print()。例如,在C头文件中,该函数看起来像
void NumPrint(void* self, FILE* stream)
并且该函数将对象实例的描述打印到流中。它需要两个参数,第一个是对应该打印的数字对象的引用,第二个是对应的流。应该打印描述
我不确定如何为此处理包装器。这是一个包装add()的简单包装器的例子,它将两个数字加在一起......
static PyObject *wrapper(PyObject *self, PyObject *args)
{
// return a C double representation
double inX = PyFloat_AsDouble(args);
// PyObject to return
PyObject* ret;
// run function
double out = c_add(inX, inX);
// build result into PyFloatObject**strong text**
ret = PyFloat_FromDouble(out);
return ret;
}
答案 0 :(得分:0)
我找到答案......
static PyObject* NumberPrintWrapper(PyObject* self, PyObject* reference){
FILE* out = NULL;
size_t size;
// create buffer
char* buffer = malloc(sizeof(*buffer));
if (buffer == NULL)
{
handle_error("buffer");
}
// map buffer to stream using open_memstream()
out = open_memstream(&buffer, &size);
if (out == NULL)
{
handle_error("open_memstream");
}
// call function that requires stream
long* s = PyLong_AsUnsignedLong(reference);
NumPrint(s, out);
// close file handle
fclose(out);
// hand over to Python
PyObject* string = PyString_FromString(buffer);
free(buffer);
return string;
}