C++ library
CallbackTestLib.hpp
#pragma once
using callback_prototype = const char* __cdecl();
extern "C" __declspec(dllexport) int __cdecl do_something(callback_prototype*);
CallbackTestLib.cpp
#include "CallbackTestLib.hpp"
#include <iostream>
using namespace std;
__declspec(dllexport) auto __cdecl do_something(callback_prototype* cb) -> int
{
if (!cb) { return 5678; }
const auto* str = cb();
cout << "Hello " << str << endl;
return 1234;
}
Python script
CallbackTest.py
import os
import sys
from ctypes import CDLL, CFUNCTYPE, c_char_p, c_int32
assert sys.maxsize > 2 ** 32, "Python x64 required"
assert sys.version_info.major == 3 and sys.version_info.minor == 8 and sys.version_info.micro == 4, "Python 3.8.4 required"
callback_prototype = CFUNCTYPE(c_char_p)
@callback_prototype
def python_callback_func() -> bytes:
return "from Python".encode("utf-8")
dll_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "CallbackTestLib.dll")
testlib = CDLL(dll_path)
testlib.do_something.restype = c_int32
testlib.do_something.argtypes = [callback_prototype]
null_return_code = testlib.do_something(callback_prototype())
assert null_return_code == 5678, "Null return code failed"
ok_return_code = testlib.do_something(python_callback_func)
assert ok_return_code == 1234, "Ok return code failed"
print("Done.")
Python output
d:/path/to/CallbackTest.py:22: RuntimeWarning: memory leak in callback function.
ok_return_code = testlib.do_something(python_callback_func)
Hello from Python
Done.
As the output shows, Python (somehow) seems to have detected a memory leak when python_callback_func
is executed, which returns bytes (UTF-8 encoded string) back to C++ where the string is being printed out.
My question is all about this: what is going on around with this warning, how to avoid/solve it?