Sending a C++ vector to a Python function

Asked

Viewed 179 times

-1

I have the following function written in python in a file. py:

def coordinate(arg):
    print arg

    return True

And an example of C++ code in a file. CPP

#include <Python.h>
#include <vector>

int main()
{

   bool result;
   std::vector<float> coords;

   Py_Initialize();

   ...

   result = ????
   Py_Finalize();

   return true;
}

How to send from C++ code to float vector coords, for the Python coordinate function()?

  • coords.data()? https://en.cppreference.com/w/cpp/container/vector/data

1 answer

2

VC will need to compile the code to create a python module...

Create a setup.py use the distutils python, this file will be responsible for creating/linking a module written in C/C++ that can later be imported into your Python Code.

setup.py basic example:

from distutils.core import setup, Extension

setup(name='NOMEMODULO', version='1.0',  \
      ext_modules=[Extension('NOMEMODULO', ['codigo.cpp'])])

Now you will have to compile to create your module in python, you will have to have a compiler installed and the module distutils properly installed in its python version...

In the folder that your C/C++ files are running a:

python setup.py install

Before running check if all Paths necessary are in the environment variables of your OS (where is the python exec, where is the compiler exec, etc)

If the above command runs without errors you will have a module that can be called inside your python code..

import NOMEMODULO

Ready now you can call the functions that exist inside your C++ code inside your Python code...

To work with vectors I recommend that you use the Numpy

I just created a simple example (testevector. c) to demonstrate how to work with vectors from your C/C++ and integrate with python with the help of Numpy (I’m using python27, but this is the basis to work on qq version):

#include <Python.h>
#include <numpy/arrayobject.h>
PyObject * testevetor()
{
          int vetor[5] = {0,1,2,3,4};
          int tamanho = 5;
          PyObject * c = PyArray_SimpleNewFromData(1,&tamanho,PyArray_INT,vetor);
    
           return (PyObject*)c;
}



static PyObject *ErrorObject;

static PyMethodDef OiMethod[] = 
{
    {"testevetor", testevetor, METH_VARARGS, "teste do vetor"},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC 
initoivetor(void)
{
    (void) Py_InitModule("oivetor", OiMethod);
    import_array();
    ErrorObject = PyString_FromString("Oi.error");
    if (PyErr_Occurred())
        Py_FatalError("can't initialize module");
}

The above Code only prints the values 0 1 2 3 4 as you can notice I am using Numpy to create an object that returns these values, just to demonstrate how it is done I created a module called oivetor and the function that returns the values is called testevetor()

Well done this you need to create a setup.py:

#build the modules

from distutils.core import setup, Extension

setup(name='oivetor', version='1.0',  \
      ext_modules=[Extension('oivetor', ['testevetor.c'])])

Just put all the files in a folder in compile (of course vc have q have a compiler and the ai distutils correctly installed and with path in the environment variable ...

Just spin one:

Python setup.py install (C:\Python27\testevetor>C:\Python27\python.exe setup.py install)

If no error happens you must have installed the module...

C:\Python27\testevetor>C:\Python27\python.exe setup.py install
running install
running build
running build_ext
building 'oivetor' extension
C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python27\Lib\site-packages\
numpy\core\include -IC:\Python27\include -IC:\Python27\PC -c testevetor.c -o bui
ld\temp.win32-2.7\Release\testevetor.o
testevetor.c:30:2: warning: no newline at end of file
writing build\temp.win32-2.7\Release\oivetor.def
C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.7\Release\testeve
tor.o build\temp.win32-2.7\Release\oivetor.def -LC:\Python27\libs -LC:\Python27\
PCbuild -lpython27 -lmsvcr90 -o build\lib.win32-2.7\oivetor.pyd
running install_lib
copying build\lib.win32-2.7\oivetor.pyd -> C:\Python27\Lib\site-packages
running install_egg_info
Removing C:\Python27\Lib\site-packages\oivetor-1.0-py2.7.egg-info
Writing C:\Python27\Lib\site-packages\oivetor-1.0-py2.7.egg-info

Here no error: let’s test ....

import oivetor
import numpy
print (numpy.array(oivetor.testevetor()))

array([0, 1, 2, 3, 4])

Working perfectly, it’s almost a tutorial that huahuhua

Use this mount to pick up audio vectors by processing in C/C++ and pass to Python ....

  • Very grateful for the answer, but if it’s not too much to ask, could you comment on the code? Another thing, what I meant by "Ready now you can call the functions that exist within your C++ code within your Python code..." and then at the end with "I use this mount to pick up audio vectors processing in C/C++ and move on to Python ...." ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.