test.cpp
#include <iostream>
#include <strsafe.h>
using namespace std;
typedef void(__stdcall* Mycallback2)(wchar_t* buff, size_t buffsize);
extern "C" __declspec(dllexport)
void TestMethod5(Mycallback2 callback)
{
wchar_t* buff = new wchar_t[MAX_PATH]; // MAX_PATH 260
StringCchPrintf(buff, MAX_PATH, L"%s", L"Test String");
if (callback) callback(buff, MAX_PATH);
wcout << buff << endl;
delete[] buff;
}
test.py
from ctypes import *
dll = CDLL(path)
MYCALLBACKTYPE = CFUNCTYPE(None, c_wchar_p, c_size_t)
dll.TestMethod5.restype = None
dll.TestMethod5.argtypes = [MYCALLBACKTYPE]
def callback(pt: c_wchar_p, ptsize: c_size_t) -> None:
pt.value = 'python string'
mycallback = MYCALLBACKTYPE(callback)
dll.TestMethod5(mycallback)
python outputs
Exception ignored on calling ctypes callback function: <function callback at 0x0000021D50DE7B80>
Traceback (most recent call last):
File "d:\MyProjects\GitRepo\CodePython\App\dlltest\main.py", line 59, in callback
pt.value = 'python string'
AttributeError: 'str' object has no attribute 'value'
I dont't know how to write to the given buffer. I specified type of pt as c_wchar_p, but the type of pt was changed to str.
I tried to just assign string to pt, of course, not worked.
Edit1:
I found a working way but not good.
MYCALLBACKTYPE = CFUNCTYPE(None, POINTER(c_wchar), c_size_t)
dll.TestMethod5.restype = None
dll.TestMethod5.argtypes = [MYCALLBACKTYPE]
def callback(pt: POINTER(c_wchar), ptsize: c_size_t) -> None:
s = 'python string'
if len(s) < ptsize:
for i in range(0,len(s)):
pt[i] = s[i]
Is there another good way..?