2

C code:

#include "Python.h"
#include <windows.h>
__declspec(dllexport) PyObject* getTheString()
{
    auto p = Py_BuildValue("s","hello");
    char * s = PyString_AsString(p);
    MessageBoxA(NULL,s,"s",0);
    return p;
}

Python code:

import ctypes
import sys
sys.path.append('./')
dll = ctypes.CDLL('pythonCall_test.dll')
print type(dll.getTheString())

Result:

<type 'int'>

How can I get pytype(str)'hello' from C code? Or is there any Pythonic way to translate this pytype(int) to pytype(str)?

It looks like no matter what I change,the returned Pyobject* is a pytype(int) no else

2
  • the messagebox shows 'hello' Commented Dec 28, 2015 at 8:33
  • 3
    Just thinking out loud: in the c code you are returning a PyObject pointer, which is just an address actually. And the python side is receiving this as an integer (since it is just an address) Commented Dec 28, 2015 at 8:46

2 Answers 2

2

By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object. (ref)

Define the type returned by your function like that:

>>> from ctypes import c_char_p
>>> dll.getTheString.restype = c_char_p # c_char_p is a pointer to a string
>>> print type(dll.getTheString())
Sign up to request clarification or add additional context in comments.

1 Comment

can i return a Python type to python code? i wanna python code receive python value from C code.but thank u for the answer
0

int is the default return type, to specify another type you need to set the function object's restype attribute. See Return types in the ctype docs for details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.