rookie
rookie

Reputation: 161

How does Python receive a string from a C function?

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

Upvotes: 2

Views: 163

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55479

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.

Upvotes: 0

Assem
Assem

Reputation: 12107

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

Upvotes: 2

Related Questions