tags:

views:

85

answers:

3

I have the following python 3 file:

import base64
import xxx

str = xxx.GetString()
str2 = base64.b64encode(str.encode())
str3 = str2.decode()
print str3

xxx is a module exported by some C++ code. This script does not work because calling Py_InitModule on this script returns NULL. The weird thing is if I create a stub xxx.py in the same directory

def GetString() :
    return "test"

and run the original script under python.exe, it works and outputs the base64 string. My question is why doesn't it like the return value of xxx.GetString? In the C++ code, it returns a string object. I hope I have explained my question well enough... this is a strange error.

A: 

Er... You have to investigate why Py_InitModule returns NULL. Posting the Python code using that module won't help.

Antoine P.
I don't know why it returns NULL - nothing is printed to the console.Oh wait. I see what you're saying. NULL is returned when I try to load the script above with Py_InitModule, not some other module.
George Edison
I fixed the question.
George Edison
A: 

Py_InitModule() is for initializing extension modules written in C, which is not what you are looking for here. If you want to import a module from C, there is a wealth of functions available in the C API: http://docs.python.org/c-api/import.html

But if your aim is really to run a script rather than import a module, you could also use one of the PyRun_XXX() functions described here: http://docs.python.org/c-api/veryhigh.html

Antoine P.
The latter is what I intended but it still doesn't run... I am wondering if it has anything to do with GetString returning a ASCII string instead of Unicode.
George Edison
Here it is: return Py_BuildValue("s","test");
George Edison
This still doesnt make a lot of sense! Please post the code that is using the result from Py_BuildValue(). Don't assume that giving some partial and elliptic information about what you are trying to do is sufficient for us to diagnose your problem precisely!
Antoine P.
Sorry, see my comment above.
George Edison
+1  A: 

I know everybody says this...but: Boost has an awesome library for exposing classes to python and getting data to and fro. If you're having problems, and looking for alternatives is an option I'd highly recommend the boost python library of the C interface. I've used them both, boost wins hands down imo.

Chris H