I'm trying to translate some simple cython to c++ :
cdef public int G = 1
and then use it in my c++ code :
#include <Python.h>
#include "test.h" // The file generated by the cython command
#include <iostream>
int main(int argc, char **argv) {
std::cout << "G : " << G << std::endl;
}
Output is :
G : 0
I've looked into the test.cpp cython-generated file, and on line 897, I have
G = 1;
So why is G evaluated to 0 in the main ?
Here are the commands used to compile :
cython.exe test.pyx -3 --cplus
g++ test.cpp test_main.cpp -IC:\Python36-32\include -LC:\Python36-32\libs -lpython36
What you generate when you use cython is a python extension module. You cannot link it directly into an executable, as it needs to be dynamically imported and linked to libpython. In that process, your extension's initialization function is run, which will cause your G to be set to 1.
So you should:
Build a python extension from your cython (using -shared and outputting a DLL).
Load python interpreter in your main. In your program, you don't even initialize python at the moment.
Import it in your main using PyImport_ImportModule("mymodule").
Untested, but your main should look like this:
#include <Python.h>
int main(int argc, char * argv[])
{
Py_Initialize();
PyObject * test_module = PyImport_ImportModule("test");
// do something with test_module
Py_Finalize();
return 0;
}
You can get G from python using PyObject_GetAttrString(), or since you declared it as cdef, you can access it directly using your OS's symbol resolution tools, such as GetProcAddress() for windows.
It may be possible to link dynamically at load time, yet still use importmodule to let python do its initialization magic, but I have no idea how to do that or if it's even possible.
Related
For a project of mine, I need to embed the Python interpreter in a wider C application, using the interpreter of an Anaconda environment. How can I do so ? I've looked online, but nothing mentions it. I'm guessing I should change something near Py_Initialize(), but what ?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#ifndef PY_SSIZE_T_CLEAN
#define PY_SSIZE_T_CLEAN
#endif
#include <Python.h>
int main()
{
Py_Initialize(); // Here ?
// Maybe something like Py_InitializeInterpreter("whatever/path") ?
PyObject* pName = PyUnicode_DecodeFSDefault("script");
PyObject* pModule = PyImport_Import(pName);
Py_DecRef(pName);
bool running = false;
while(running)
{
//whatever I need to do
}
Py_DecRef(pModule);
Py_Finalize();
return EXIT_SUCCESS;
}
EDIT : I'd just like to point out one thing : I'm not a Python dev by any means, I just need to call Python functions from my C application. The Python itself is coded by someone else, so I don't have much knowledge at all about how it works.
I have been trying to work out how to make a .pyd (Python Extension Module) file from a C script (without swig or anything else except MinGW) and have successfully built it into a .pyd.
The problem however occurs when I try and import the module.
If I run it the module runs successfully (as far as I can see) and then an error appears saying Python Has Stopped Working and it closes without executing the rest of the program.
Here is my C script (test.c):
#include <python.h>
int main()
{
PyInit_test();
return 0;
}
int PyInit_test()
{
printf("hello world");
}
And Python Script (file.py):
import test
print('Run From Python Extension')
I compiled the script with:
gcc -c file.py
gcc -shared -o test.pyd test.c
I can't find any errors when compiling in command prompt and am using python 3.6 (running on Windows 10).
I can't find much on the subject and would prefer to keep away from Cython (I already know C) and Swig.
Any help to tell me what is wrong would be fantastic.
Creating a Python extension is completely different than writing regular C code. What you have done is simply creating a valid C program but that doesn't make sense for Python.
That's how your program should look like (it's just a skeleton, not the proper, working code):
#include <Python.h>
#include <stdlib.h>
static PyObject* test(PyObject* self, PyObject* args)
{
printf("hello world");
return NULL;
}
static PyMethodDef test_methods[] = {
{"test", test, METH_VARARGS, "My test method."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC init_test_methods() {
Py_InitModule("test", test_methods);
}
int main(int argc, char** argv)
{
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(argv[0]);
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Add a static module */
init_test_methods();
}
I recommend you read more about this at the following link: http://dan.iel.fm/posts/python-c-extensions/ as well as in the official docs.
I'm making an Qt Quick GUI application(for windows), which uses OpenGL and C++ for some computationally intensive stuff. I want to embed python code into the app, for doing some stuff which is comparatively easier in python.
Basically, I just want the c++ code to call a function in a python script and let the script do the job, then store the returned data in a variable(string, or float etc.) for further use. I'm using Qt creator, and I got python3 lib for MinGW compiler. I tried some code, but its looks like python lib is not quite compatible with Qt creator. IS using pyqt for this will be a good idea? What will be the best and easiest way to do this ?
EDIT: This is the basic code I tried, first it gave me an error saying, cannot find pyconfig.h. Then I added an INCUDEPATH to my python34 include directory.
#include "mainwindow.h"
#include <QApplication>
#include <boost/python.hpp>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
using namespace boost::python;
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
Py_Initialize();
pName = PyString_FromString(argv[1]);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, argv[2]);
if (PyCallable_Check(pFunc))
{
PyObject_CallObject(pFunc, NULL);
} else
{
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
return a.exec();
}
My .pro file:
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = TestWidgetApp
TEMPLATE = app
INCLUDEPATH += C:/boost_1_57_0
INCLUDEPATH += C:/Python34/include
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
OTHER_FILES +=
Then the following errors:
C:\Python34\include\object.h:435: error: C2059: syntax error : ';'
C:\Python34\include\object.h:435: error: C2238: unexpected token(s) preceding ';'
C:\Users\Amol\Desktop\TestWidgetApp\main.cpp:19: error: C3861: 'PyString_FromString': identifier not found
The problem here is that Python 3.4 has a struct member called "slots", (file object.h, in the typedef for PyType_Spec), which Qt defines out from under you so that you can say things like:
public slots:
in your code. The solution is to add:
#undef slots
just before you include Python.h, and to redefine it before you include anything that uses "slots" in the way that Qt does:
#undef slots
#include <Python.h>
#define slots
#include "myinclude.h"
#include <QString>
A bit of a hack (because you're depending on a particular definition of slots in Qt), but it should get you going.
I have removed all the Qt code from your example and then I tried to compile it (Qt has nothing to do with your compile error). And it compiles for me. The difference was I used the include files from Python 2.7.
So I did a little search for the string PyString_FromString in the folders: C:\Python33\includes (I noted you use python 3.4 and not 3.3 but I suspect this is a 3.x thing) and C:\Python27\includes.
Results:
Python 3.3
Python 2.7
So, apparently, Python 3.4 is not supported by your BoostPython version.
Python3 has no PyString_FromString function. Python3 str type internally is unicode objects with complex structure.
Use PyUnicode_FromString or PyUnicode_FromStringAndSize for constructing str object from UTF-8 encoded C string (char*).
Move your
#include "boost/python.hpp"
...to be before your other includes and it will resolve your problem.
The actual issue is as Scott Deerwester described in his answer.
I'm a regular C user, but pretty new to Python.
I have a library written in C for performing calculations that I'm trying to make callable from a Python script. The library needs some user defined routines, for which I am trying to allow the use of Python scripts.
I am running into a problem which demonstrates to me that I do not understand something very fundamental. Here is the code for a simple program I cannot get to run. It should print to the screen the result of 7 (2+5).
The Python script test.py is called first. It loads ctypes and the library libfoo.so, and calls the C routine c_do_work:
from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')
print "Python 1: Going in..."
lib.c_do_work(2,5)
The C function c_do_work is defined in the library libfoo.so, which has the single module test.c. This routine should run the Python script my_func.py, which defines the function find_sum. A Python interpreter is initialized here:
//gcc test.c -I/usr/include/python2.7/ -L/usr/lib/python2.7/ -lpython2.7 -lm -fPIC -c
//gcc -shared -Wl,-soname,libfoo.so -o libfoo.so test.o
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
void c_do_work(int a,int b)
{
Py_Initialize();
PyObject* main_module = PyImport_AddModule("__main__");
PyObject* main_dict = PyModule_GetDict(main_module);
FILE* file_1 = fopen("my_func.py", "r");
PyRun_File(file_1, "my_func.py",Py_file_input,main_dict, main_dict);
PyObject* expression = PyDict_GetItemString(main_dict,"find_sum");
printf("C: calling Python function...\n");
PyObject_CallFunction(expression,"ii",a,b);
//Clean up
fclose(file_1);
Py_Finalize();
}
Lastly, the Python script my_func.py:
def find_sum(a, b):
print a+b
When I run "python test.py", I get a segmentation fault at the second line of the C function:
PyObject* main_module = PyImport_AddModule("__main__");
Why is this happening? If I slightly rewrite the C routine so it is main, and run that program directly, I get the desired result. The problem seems to be related to having a Python interpreter calling a routine that initializes a Python interpreter.
So I have a Python program that's finding .txt file directories and then passing those directories as a list(I believe) to my C++ program. The problem I am having is that I am not sure how to pass the list to C++ properly. I have used :
subprocess.call(["path for C++ executable"] + file_list)
where file_list is the [] of txt file directories.
My arguments that my C++ code accepts are:
int main (int argc, string argv[])
Is this correct or should I be using a vector? When I do use this as my argument and try to print out the list I get the directory of my executable, the list, and then smiley faces, symbols, and then the program crashes.
Any suggestions? My main point that I am trying to find out is the proper syntax of utilizing subprocess.call. Any help would be appreciated! thanks!
Another option is to use cython, (not a direct answer). Here is a simple complete example:
Suppose you have the following files:
cython_file.cpp
python_file.py
setup.py
sum_my_vector.cpp
sum_my_vector.h
setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension(
name="cython_file",
sources=["cython_file.pyx", "sum_my_vector.cpp"],
extra_compile_args=["-std=c++11"],
language="c++",
)]
setup(
name = 'cython_file',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
)
cython_file.pyx
from libcpp.vector cimport vector
cdef extern from "sum_my_vector.h":
int sum_my_vector(vector[int] my_vector)
def sum_my_vector_cpp(my_list):
cdef vector[int] my_vector = my_list
return sum_my_vector(my_vector)
sum_my_vector.cpp
#include <iostream>
#include <vector>
#include "sum_my_vector.h"
using namespace::std;
int sum_my_vector(vector<int> my_vector)
{
int my_sum = 0;
for (auto iv = my_vector.begin(); iv != my_vector.end(); iv++)
my_sum += *iv;
return my_sum;
}
sum_my_vector.h
#ifndef SUM_MY_VECTOR
#define SUM_MY_VECTOR
using namespace::std;
int sum_my_vector(vector<int> my_vector);
#endif
python_file.py
from cython_file import sum_my_vector_cpp
print sum_my_vector_cpp([1,2,3,5])
Now run
python setup.py build_ext --inplace
and the you can run the python file
python python_file.py
11
"Passing a list through Python to C++"
An alternative approach would be to use Boost.Python, this may not answer your question directly, but still its worth pointing out another solution.
#include <boost/python.hpp>
#include <vector>
#include <string>
void get_dir_list( boost::python::list dir_list )
{
for (int i = 0; i < len(dir_list); ++i)
{
std::string x = boost::python::extract<std::string>(dir_list[i]);
// perform stuffs
std::cout << "This is " << x << std::endl ;
}
}
BOOST_PYTHON_MODULE(get_dir_list)
{
def("get_dir_list", get_dir_list);
}
Compiled Using :
g++ main.cpp -shared -fPIC -o get_dir_list.so -I/usr/include/python2.7 -lboost_python
Usage :
import get_dir_list
import os
get_dir_list.get_dir_list(os.listdir('.'))
Live Demo Here
I'll post this alternative solution since it would also work for other long lists of strings that needed to be passed.
In your Python script create a text file (I'll call it "masterFile") and write the file paths to the masterFile. You could give each file path a separate line. Then pass the masterFile's file path to your C++ program. This way you don't have to worry about the length of your command line arguments. Let your C++ program open and read the file for processing.
You can use something like os.remove() to get rid of the masterFile in your Python script once the C++ program has finished.
Also, you mentioned in the comments that you need to do different tasks dependent on different file paths: A suggestion would be to add a char at the beginning of each line in the masterFile to signal what needs to be done for the particular file. Example:
a Random/path/aFile.txt # a could mean do task 1
b Random2/path2/differentFile.c # b could mean do task 2
You pass a list to subprocess.call. subprocess.call converts this to what is needed for the system (which may vary, but certainly isn't a Python list). The system then arranges for this to be copied somewhere in the new process, and sets up the standard arguments to main, which are int, char**. In your C++ program, you must define main as int main( int argc, char** argv ); nothing else will work. (At least... a system could support int main( std::string const& ) or some such as an extension. But I've never heard of one that did.)