Best way to pass a python list to a cpp function in ROOT Jupyter

In a Jupyter notebook with the ROOT kernel, I’m trying to pass a list of string values which was generated in a Python cell to a cpp function in a cell marked %%cpp. I tried (just to see if it might work by chance) defining the cpp function as

void func(char** lst, int lst_size)

and

void func(vector<string> lst)

but in both cases I get the ‘could not convert argument 1’ exception.
What’s the correct way to do it?

Have you tried defining/casting your list as a numpy.array of strings?

I remember trying to pass a numpy array but I also had a ‘couldn’t convert’ exception…

I just figured it out though, using ctypes (https://stackoverflow.com/questions/3494598/passing-a-list-of-strings-to-from-python-ctypes-to-c-function-expecting-char). One needs to use this intermediate Python function:

def call_c(L):
arr = (ctypes.c_char_p * len(L))()
arr[:] = [x.encode(‘utf-8’) for x in L]
ROOT.func(len(L), arr)

Hope this is helpful to somebody.

1 Like

Nice, might come in handy one day!

Next time, you might want to fence your code with triple back quotes (```), which makes it a code block and conserves whitespace and applies syntax highlighting:

import ctypes

def call_c(L):
    arr = (ctypes.c_char_p * len(L))()
    arr[:] = [x.encode('utf-8') for x in L]
    ROOT.func(len(L), arr)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.