cuda and ctypes: a simple problem

Hi,

I’m trying to load _test.so’s through ctypes. It only works if the function in _test.so is called main (!).

My python code is:

#! /usr/bin/python

import ctypes
libc = ctypes.cdll.LoadLibrary("_test.so")
libc.main.argtype = [ctypes.c_int]
res = libc.main(3)
print 'function returns', res

The cuda code is:

#include <iostream>

using namespace std;

__host__ int main(int n)
{
	for(int i=0; i<n; i++)
		cout << "Hello, world!" << endl;

	return 0;
}

I compile the game using

nvcc -c test.cu -arch sm_20 -Xcompiler -fPIC
g++ -shared test.o -o _test.so -L/usr/local/cuda/lib64 -lcudart -lcuda

I’m curious to know why the example only works if the function is called main??

Thanks, Jus

The issue (after some experimenting) seems to be that putting the “host” directive on a function forces it to get C+±style name mangling in the output object file, except in the case of main(). I assume that main() has been given a special case, due to its obvious significance when starting C and C++ programs.

There were two solutions I found:

  1. Remove host from functions you want to call from Python. The host directive is almost never used except with device to force a function to be compiled both for the CPU and the GPU. By default, all functions without either directive are compiled for the CPU.

  2. Enclose functions you want to call from Python in an extern “C” block:

extern "C" {
  __host__ int other(int n)
  {
          for(int i=0; i<n; i++)
                  cout << "Hello, world!" << endl;

          return 0;
  }
}

Thanks seibert! Now, it works perfectly!