如何在python中将包含十六进制值的unsigned char *数组写入文件

时间:2013-11-18 18:49:40

标签: c++ python c ctypes

我有一个C dll,它将PDF文件作为包含十六进制值的unsigned char *返回。如何使用ctypes检索此数组并将其保存到“发掘”PDF文件?

例如在C中我这样做:

unsigned char* manual = getPluginManualAsPDF(mPlugin);
long nrOfBytes        = getPluginManualNrOfBytes(mPlugin);

string tempFile(mtk::JoinPath(getTempFolder(getRRHandleFromPlugin(mPlugin)), "AddNoisePluginDoc.pdf"));
ofstream temp(tempFile.c_str(), std::ios::binary);

long byteNr = 0;
while (byteNr < nrOfBytes)
{
    temp<< manual[byteNr];
    byteNr++;
}

temp.close();

    //Spanw an external pdf reader
    ShellExecute(Handle, "open", tempFile.c_str(), NULL, NULL,SW_SHOWNORMAL) ;
}

我试图通过CTypes访问相同的函数(getPluginManualAsPDF和getPluginManualNrOfBytes),即

rrpLib.getPluginManualAsPDF.restype = c_buffer
def getPluginManualAsPDF(pluginHandle):
    return rrpLib.getPluginManualAsPDF(pluginHandle)

def getPluginManualNrOfBytes(pluginHandle):
    return rrpLib.getPluginManualNrOfBytes(pluginHandle)

但是getPluginManualAsPDF()函数的返回有问题..任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

假设您的getPluginManualAsPDFgetPluginManualNrOfBytes具有以下原型:

/* FIXME: the type of `mPlugin` isn't clear, is it void * ? */

unsigned char * getPluginManualAsPDF(void *mPlugin) {
  static unsigned char manual[] = {1, 2, 3};
  return manual;
}

long getPluginManualNrOfBytes(void *mPlugin) {
  return 12345;
}

您可以使用以下方法调用这两个函数:

from ctypes import *

rrpLib = cdll.rrpLib # or windll if it use STDCALL

getPluginManualAsPDF = rrpLib.getPluginManualAsPDF
getPluginManualAsPDF.restype = POINTER(c_ubyte)
getPluginManualAsPDF.argtypes = [c_void_p]

getPluginManualNrOfBytes = rrpLib.getPluginManualNrOfBytes
getPluginManualNrOfBytes.restype = c_long
getPluginManualNrOfBytes.argtypes = [c_void_p]

例如:

# gcc -Wall rrpLib.c -shared -o rrpLib.dll
# python
>>> from ctypes import *
>>>
>>> rrpLib = cdll.rrpLib # or windll if it uses STDCALL
>>>
>>> getPluginManualAsPDF = rrpLib.getPluginManualAsPDF
>>> getPluginManualAsPDF.restype = POINTER(c_ubyte)
>>> getPluginManualAsPDF.argtypes = [c_void_p]
>>>
>>> getPluginManualNrOfBytes = rrpLib.getPluginManualNrOfBytes
>>> getPluginManualNrOfBytes.restype = c_long
>>> getPluginManualNrOfBytes.argtypes = [c_void_p]
>>>
>>> getPluginManualAsPDF(None)[0]
1
>>> getPluginManualAsPDF(None)[1]
2
>>> getPluginManualAsPDF(None)[2]
3
>>>
>>>
>>> ptr = getPluginManualAsPDF(None)
>>> manual = cast(ptr, POINTER(c_ubyte * 3))[0]
>>> manual
<__main__.c_ubyte_Array_3 object at 0x017801C0>
>>> open('out.txt', 'wb').write(bytearray(manual))
>>> open('out.txt').read()
'\x01\x02\x03'
>>>
>>>
>>> getPluginManualNrOfBytes(None)
12345
>>>