以下代码适用于Python 2:
from ctypes import *
## Setup python file -> c 'FILE *' conversion :
class FILE(Structure):
pass
FILE_P = POINTER(FILE)
PyFile_AsFile = pythonapi.PyFile_AsFile # problem here
PyFile_AsFile.argtypes = [py_object]
PyFile_AsFile.restype = FILE_P
fp = open(filename,'wb')
gd.gdImagePng(img, PyFile_AsFile(fp))
Run Code Online (Sandbox Code Playgroud)
但在Python 3中,pythonapi中没有PyFile_AsFile.
代码是testPixelOps.py之外的代码.
假设我有这个C代码:
#include <stdio.h>
// Of course, these functions are simplified for the purposes of this question.
// The actual functions are more complex and may receive additional arguments.
void printout() {
puts("Hello");
}
void printhere(FILE* f) {
fputs("Hello\n", f);
}
Run Code Online (Sandbox Code Playgroud)
我正在编译为共享对象(DLL): gcc -Wall -std=c99 -fPIC -shared example.c -o example.so
然后我将它导入到在Jupyter或IPython笔记本中运行的Python 3.x中:
import ctypes
example = ctypes.cdll.LoadLibrary('./example.so')
printout = example.printout
printout.argtypes = ()
printout.restype = None
printhere = example.printhere
printhere.argtypes = (ctypes.c_void_p) …Run Code Online (Sandbox Code Playgroud)