开发者

How to create and assign a Python variable in C?

I've initialized the Python environment by

Py_Initialize();

I have no external Python module imported into the environment and everything works well. But when I need to pass a C string into this environment, I am lost...

I was thinking to add a function in the environment to assign the variable like the following code do.

char *str;
str="\
def assign_var(str):\
    global string\
    string = str";
PyRun_SimpleString(str);

And then call this function in C and pass the converted C string as the arguments.

I don't think all I mentioned above is a good way solve the problem...

How can I make this work?

Solution:

Finally, here's the solution with Peter Mortensen's help. (Thanks Peter Mortensen!)

As the python environment I've initialized is a pure empty environment(without any imported modules). I use

py_main = PyImport_AddModule("__main__");

to get a hook to the main environment. and then call

PyModule_AddStringConstant(py_main, "string_name", str);

to bring the C string into the python environment.

To verify everything is done, just try:

PyRun_S开发者_如何学PythonimpleString("print dir()");
PyRun_SimpleString("print string_name");

and you'll see you "string_name" string appears in the dir() list and make it print by python!


This should do what you want:

char *cStr = "Some text here.";

PyObject *pyStr = Py_BuildValue("s", cStr);

http://docs.python.org/c-api/arg.html#Py_BuildValue

Of course if you're using Python 3 (or use it in the future), there may be situations where you'd want to use "y" instead of "s" and get a bytes object rather than a str.

UPDATE: Woops, I forgot the even easier way of doing it.

PyObject *pyStr = PyString_FromString(cStr);

http://docs.python.org/c-api/string.html#PyString_FromString

(It'd be PyBytes_FromString() in Python 3.)

You might want to take a look at http://docs.python.org/extending/embedding.html for some more information.


Here's something else you might want to try. See

http://docs.python.org/c-api/module.html#PyModule_AddObject
Or possibly
http://docs.python.org/c-api/module.html#PyModule_AddStringConstant

With the former it'd be something like

errorcheck = PyModule_AddObject(embmodule, "str", pyStr);

And with the latter, something like

errorcheck = PyModule_AddStringConstant(embmodule, "str", cStr);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜