Using numpy on an embedded python interpreter using VS2008 under Windows 7 - c++

Let's take a look at my project.
I'm using Visual Studio 2008, Python 2.7 and numpy 1.8.1 (but I have tried several versions and none worked). My project is being compiled on debug mode.
It's a very simple code:
/* = Main.cpp file = */
#include "stdafx.h"
#include "Python.h"
int _tmain(int argc, _TCHAR* argv[])
{
PyObject *pName, *main;
Py_Initialize();
pName = PyUnicode_FromString("main");
main = PyImport_Import(pName);
Py_XDECREF(pName);
if (main != NULL)
{
printf("Python Module Loaded!!\n");
}
else
{
printf("Unable to load Python Module!!\n");
}
return 0;
}
And
""" = Main.py file = """
print 'Hello World!'
If I execute this code, I get:
As it is expected.
My problem arises as soon as I change main.py into:
""" = Main.py file = """
import numpy
print 'Hello World!'
Then I get the:
I have tried to run main.py separately on a python interpreter (not embedding it into C++) and then everything works just fine:
I have also tried a modification on the main.cpp as follows:
#include "stdafx.h"
#include "Python.h"
int _tmain(int argc, _TCHAR* argv[])
{
PyObject *pName, *main;
Py_Initialize();
PyRun_SimpleString("import numpy");
return 0;
}
From this code the output is:
Finally I also tried compiling original version of main.cpp code in release mode and then the output is:
So, my question here is: What can I do to get numpy working under debug compilations using an embedded interpreter on Visual Studio 2008?

You know you have to have use a python debug version built don't you? That is probably your problem. (I would leave a comment but no rep ): )

Related

Octave Interpreter: "listdlg is not available in this version of octave"

I've successfully created a standalone executable of my m-file with mkoct and it will execute the first few lines of code, including uigetfile where I can select a file from my PC. When the interpreter tries to execute the listdlg function I get the error: listdlg is not available for this version of octave
Inside listdlg.m, I can see this error is caused by if (__octave_link_enabled__ ()) on line 150. This is not set when octave is started with octave -cli. It is set however when octave --no-gui is used which I think is what I want the interpreter to use.
So, my question is, is there any way of specifying through the C++ API how octave is started?
I'm using the following C++ code to run my script:
#include <iostream>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
int
main (int argc, char *argvc[])
{
string_vector argv (2);
argv(0) = "embedded";
argv(1) = "-q";
octave_main (2, argv.c_str_vec(), 1);
octave_value_list in = octave_value (argvc[1]);
octave_value_list out = feval ("my script");
if (!error_state && out.length () > 0)
{
}
else
{
std::cout << "invalid\n";
}
return 0;
}

Segmentation fault occurs when PyRun_SimpleFile is called repeatedly

I want to embed a python code written in version 3.5 in c++. Also, the python script needs to be executed as the whole script repeatedly. My code as follows. It executes well for the first iteration and gives a segmentation fault at the second iteration.
main.cpp:
#include <Python.h>
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
int i = 0;
while(i<3){
cout<<"start"<<endl;
Py_Initialize();
FILE* file;
wchar_t* _argv[argc];
for(int i=0; i<argc; i++){
wchar_t *arg = Py_DecodeLocale(argv[i], NULL);
_argv[i] = arg;
}
PySys_SetArgv(argc, _argv);
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyUnicode_FromString("."));
file = fopen("./example.py","r");
PyRun_SimpleFile(file, "./example.py");
fclose(file);
Py_Finalize();
cout<<"Done"<<endl;
i++;
}
return 0;
}
example.py:
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'initial learning rate')
def main(argv=None):
print(FLAGS.learning_rate)
if __name__ == '__main__':
main()
I build the project using:
cmake --build . --target Demo -- -j 2
and executed as:
./Demo --learning_rate 0.02
The output was:
start
0.02
Done
start
Segmentation fault (core dumped)
Then I replaced the content of "example.py" as:
print("Hi")
The output was:
start
Hi
Done
start
Hi
Done
start
Hi
Done
How can I fix the above mentioned segmentation fault ?
See the docs
Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

Problems with building OpenCv with Xcode. Cannot find opencv2/opencv.hpp file

I have installed OpenCv with Homebrew on my MacOs. I have added libopencv 4.0.1.dylib in Xcode. When I try to build, Xcode cannot find the files. Any suggestions?
I changed my path but still have problems.
Main code:
#include <iostream>
#include <opencv4/opencv2/opencv.hpp>
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
Build settings including path:
Error messages:

Linking against libuv

I wanted to try using libuv in dlang. I downloaded the dlang bindings like this:
git clone git#github.com:tamediadigital/libuv.git
Now what I do next to get my "hello world" running?
I tried this:
ldc2 hello.d -luv
But it said:
ldc2: Unknown command line argument '-luv'. Try: 'ldc2 -help'
ldc2: Did you mean '-v'?
I think I need to tell the compiler where the library bindings are located.
And then import something in the source code, probably with import libuv;?
Here is the 'hello world' code I want to "port" to D:
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
int main() {
uv_loop_t *loop = malloc(sizeof(uv_loop_t));
uv_loop_init(loop);
printf("Now quitting.\n");
uv_run(loop, UV_RUN_DEFAULT);
uv_loop_close(loop);
free(loop);
return 0;
}
Here is the bindings github page: https://github.com/tamediadigital/libuv
Library home page: http://www.libuv.org
First that was a wrong bindings, here are the good ones: https://github.com/changloong/libuv
Assuming you did git clonegit#github.com:changloong/libuv.git in current dir.
Compile:
ldc2 hello.d -I=libuv/deimos/libuv/ -I=libuv/ -L=-luv
The source:
import uv;
import core.memory;
import std.stdio;
int main(){
uv_loop_t *loop = new uv_loop_t;
uv_loop_init(loop);
printf("Now quitting.\n");
uv_run(loop, uv_run_mode.UV_RUN_DEFAULT);
uv_loop_close(loop);
return 0;
}
Hope it helps someone to get started with using C libs in D.

python code to c++ lib or dll

I have some python code that I want to use from C++, I want to build it in lib or dll? how can I do it?
code have dependencies:
import socket
import string
import struct
import sys
and maybe PIL
You can use cython and write thin wrapper to export it to C
Cython lib helloWorld.pyx:
import sys
sys.path.append(".") #yourlib is in current folder
import yourlib #you can import any python module
cdef public void helloWorld():
print "Hello World Cython!"
yourlib.helloWorld("Python")
cdef public int my_sum(int x, int y):
return x*x+y
from libcpp.string cimport string
cdef public string testString( string sx, string sy ):
x = int(sx.c_str())
y = int(sy.c_str())
ret= "%d*%d+%d=%d"%(x,x,y,my_sum(x,y))
cdef char* ret2= ret
return string( ret2 )
Compile with cython (create helloWorld.cpp, helloWorld.h):
cython --cplus helloWorld.pyx
Your code program.cpp:
#include <string>
#include <iostream>
#include "Python.h"
#include "helloWorld.h" // it's cpp header so remove __PYX_EXTERN_C (bug)
int main(int argc, char *argv[]) {
Py_Initialize(); //start python interpreter
inithelloWorld(); //run module helloWorld
helloWorld();
std::cout << testString("6","6") << std::endl; #it's fast!
Py_Finalize();
return 0;
}
Compile and run:
g++ program.cpp helloWorld.cpp -I/usr/include/python2.7/ -lpython2.7
./a.out
Hello World Cython!
Hello World Python!
6*6+6=42
Another way is to use boost::python
Your code program.cpp:
#include <string>
#include <iostream>
#include <boost/python.hpp>
int main(int argc, char *argv[]) {
Py_Initialize();
boost::python::object sys = boost::python::import("sys");
sys.attr("path").attr("append")(".");
boost::python::object main_module = boost::python::import("yourlib");
main_module.attr("helloWorld")("boost_python");
boost::python::object ret= main_module.attr( "my_sum" )( 10, 10 );
std::cout << boost::python::extract<char const*>(ret) << std::endl;
Py_Finalize();
return 0;
}
Compile and run:
g++ program.cpp -I/usr/include/python2.7/ -lpython2.7 -lpython_boost
./a.out
Hello World boost_python!
10*10+10=110
You might want to check how to embed python in another application (http://docs.python.org/extending/embedding.html).