Ask Your Question
0

How can you import C++ code into a Jupyter notebook?

asked 2020-02-14 16:58:02 +0200

jdoolitt gravatar image

I have a c++ function that I would like to use with Jupyter. I'd like to be able to call it from the main python thread. A minimal example would be something like the following:

#begin c code definition

#include <vector>
#include <iostream>
void printout(std::vector<int> input){
    std::vector<int>::iterator start;
    std::vector<int>::iterator end;
    end=input.end();
    for (start=input.begin();start!=end;++start){
        std::cout<< *start;
    }
    std::cout<< std::endl;
}

int main(){
    std::vector<int> sample{1,2,3};
    printout(sample);
    return 0;
}

#switch back to python
printout((1,2,3))

I don't particularly need to call the function or run the main thread in C++, the main() is included to show how this function would be used in the C++ context. Broadly, I want something like the reverse of Cythonize

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2020-02-15 11:07:52 +0200

vdelecroix gravatar image

In Python (1, 2, 3) is a tuple. There is no way a program will automatically convert it into a std::vector<int> in Python. The reason is that it does not make much sense: tuple are heterogeneous ((1, "hello", 3.0) is valid), Python integer type supports arbitrary precision integers such as 3**100 which would not fit to a C++ int, etc.

Secondly, if you have a main in your C++ file then the compiler will generate you an executable. Which is not what you want here.

That being said it is very easy to use C++ from Python. You just want to use Cython. That works perfectly fine in Jupyter.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2020-02-14 16:58:02 +0200

Seen: 1,464 times

Last updated: Feb 15 '20