Passing a python str as LPCSTR to a c++ dll

880 Views Asked by At

I have a simple c++ dll that calls the MessageBox to display text

#include <Windows.h>

#define LIBDLL extern "C" __declspec(dllexport)

LIBDLL void Display(LPCTSTR lpInput) {
    MessageBox(0, lpInput, 0, 0);
}

bool __stdcall DllMain(void* hModule, unsigned long dwReason, void* lpReserved) {
switch (dwReason)
{

case 1:
    break;
case 0:
    break;

case 2:
    break;

case 3:
    break;

}

return true;
}

And the Python code only pass a string to the Display in the dll , it looks like this

import ctypes
sampledll = ctypes.WinDLL('SampleDll.dll')
sampledll.Display('Some Text')

And it only displays the first letter , even if I'm using std::cout

MessageBox output

How to I make it display the all text I passed to it?

1

There are 1 best solutions below

0
On BEST ANSWER

Finally fix this. Turns out that I have to encode the text before I pass it to dll.

So instead of doing this

sampledll.Display('Some Text')

It should be done like this

sampledll.Display('Some Text'.encode('utf-8))