Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython: call function from external C file

Tags:

cython

After Cython's "Hello World" and the example of calling a function in the C math libraries here, what I really want to do is to have C code of my own in a separate file and use it from Cython. Following this, I modify the setup.py file:

sourcefiles = ['hello2_caller.pyx', 'hello2.c']

This is hello2.c (main is just there to compile and test it separately---though that product isn't present for the test:

#import <stdio.h>

void f() {
    printf("%s", "Hello world!\n");
}

int main(int argc, const char* argv[]) {
    f();
    return 0;
}

This is hello2_caller.pyx

cdef extern from "hello2.c":
    void f()

cpdef myf():
    f()

I get:

In file included from hello2_caller.c:219:
hello2.c:3: warning: function declaration isn’t a prototype

So I guess I'm failing to provide a header in some way.. though just feeding setup.py a standard header like 'hello2.h' doesn't work. Can you point me to a working example or explain what I'm doing wrong. Thanks.

like image 943
telliott99 Avatar asked Dec 23 '10 13:12

telliott99


People also ask

Does Cython use C or C++?

Cython is a programming language that blends Python with the static type system of C and C++. cython is a compiler that translates Cython source code into efficient C or C++ source code. This source can then be compiled into a Python extension module or a standalone executable.

What is Cdef extern?

The cdef extern from clause does three things: It directs Cython to place a #include statement for the named header file in the generated C code. It prevents Cython from generating any C code for the declarations found in the associated block.

Does Cython compile to C?

The Cython language is a superset of Python that compiles to C, yielding performance boosts that can range from a few percent to several orders of magnitude, depending on the task at hand. For work that is bound by Python's native object types, the speedups won't be large.


1 Answers

Thanks to help from the Cython users' list here.
My writeup here.

Bottom line: this is only a warning, that is not fixed by a declaration of f(), but the compiled .so works. I'm still not sure how you would provide a .h file to Cython or if there is a better way to do this.

And there's a couple of errors: should be #include, and don't list the .c file in sourcfiles.

like image 58
telliott99 Avatar answered Oct 23 '22 10:10

telliott99