Skip to content

Call C++ function using ctypes py_object argument on windows doesn't work #114754

Open
@gtwpro

Description

@gtwpro

Bug report

Bug description:

I get an access violation. I am using a c++ dll with a single function that tries to extract a string from a PyObject. This is from similar examples posted in stackoverflow. Passing a c_char_p (to a function taking a c_char_p) and returning a PyObject * works fine. Normal c_char_p and c_int work fine.

Load a C++ dll and call a function with an object. Set correct path.

Using msvc 2022 and Python 3.9.

Python (using PYFUNCTYPE, WINFUNCTYPE or CFUNCTYPE makes no difference):

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(y)

print(z)

Create C++ x64 string.dll adding a single function. I have verified the address is correctly passed through, but then I get internal errors inside Python code when calling the PyArg_* functions. Nowhere does the documentation state that any state setup is needed to use these functions in this situation.

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);
	}
}

CPython versions tested on:

3.9

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions