在python中传递指向c ++函数的指针

时间:2015-07-22 19:41:48

标签: python django pointers structure ctypes

我尝试调用Windows dll的函数,称为DISM。

HRESULT WINAPI DismGetLastErrorMessage(
   _Out_ DismString** ErrorMessage 
);

这是一个例子:

HRESULT hr = S_OK;
DismString* ErrorMessage;

hr = DismGetLastErrorMessage(&ErrorMessage);

请参阅https://msdn.microsoft.com/en-us/library/windows/desktop/hh824754.aspx

结构看起来像

typedef struct _DismString
{
    PCWSTR Value;
}
DismString;

而Value是“以null结尾的Unicode字符串。”

这是我的代码: models.py

from django.db import models
from ctypes import *

class DismString(Structure):
_fields_ = [("Value", c_wchar_p)]

class DismManager(models.Model):

class Meta:
    abstract = True

def __init__(self, dll):

    self.hDism = OleDLL(dll)



def GetLastErrorMessage(self):
    self.hDism.DismDelete.restype = HRESULT
    self.hDism.DismDelete.argtypes = [POINTER(DismString)]
    s = DismString()
    try:
        test = self.hDism.DismGetLastErrorMessage(byref(s))
        print(test)
        #print(s)
        return s
    except WindowsError as e:
        return print("Error message", e.strerror, "\nError code", e)

views.py

from ctypes import OleDLL
from django.http import HttpResponse

from api.models import DismManager

def index(request):

    # Load library
    obj = DismManager("C:\\Program Files (x86)\\Windows Kits\\8.0\Assessment and Deployment Kit\\Deployment Tools\\amd64\\DISM\\dismapi.dll")

    obj.Init(2, u"C:\\newDism")

    session = obj.OpenSession(u"C:\\mounter") # throws an error
    last_error = obj.GetLastErrorMessage() # want to catch the error with it
    print(last_error.Value) # throws *** UnicodeEncodeError: 'charmap' codec can't encode character '\ua0b0' in position 1: character maps to <undefined>

    return HttpResponse("Hello, world.")

看起来我无法获得正确的返回字符串。我得到一个错误或一个不可读的字符串。 当我写last.error.encode()时,它返回b'\ xea \ x82 \ xb0P'。

我希望有人可以提供帮助。

0 个答案:

没有答案