I get an access violation. I am using a c++ dll with a single function that tries to extract a string from a PyObject. It seems the PyObject *args argument is not right type. This is from similar examples posted elsewhere. Passing a c_char_p (to a function taking a c_char_p) and returning a PyObject * works fine.
Load a C++ dll and call a function with an object. Set correct path.
Using msvc 2022 and Python 3.9.
Python:
import ctypes
import sys
import os
y = __file__
str_path = os.path.dirname(os.path.realpath("..\\..\\string\\x64\\Debug\\string.dll"))
handle = ctypes.CDLL(str_path + "/string.dll")
handle.My_Function3.argtypes = [ctypes.py_object]
handle.My_Function3.restype = ctypes.py_object
z = handle.My_Function3(ctypes.py_object(y))
print(z)
Create C++ string.dll adding a single function.
C++ file added to string.dll (added to Windows dll) dllmain.cop is unchanged:
function.cpp:
#include "pch.h"
#define PY_SSIZE_T_CLEAN
#include <Python.h>
char s[100];
static PyObject *MyError;
extern "C"
{
__declspec(dllexport) PyObject* __stdcall My_Function3(PyObject *args)
{
const char* str;
char s[100];
// Code fails here with access violation
if (!PyArg_ParseTuple(args, "s", &str))
return NULL;
if (strlen(str) > 100)
{
PyErr_SetString(MyError, "Error: string too long");
return NULL;
}
strcat_s(s, 100, str);
return Py_BuildValue("s", s);
}
}