cfly

Warning

CFly is under development. It may change without backward compatibility until the first stable version is reached. The first stable version will be 1.0.0

Installation

Install cfly with pip:

$ pip install cfly

Reference

cfly.build_module(name, source=None, sources=None, preprocess=None, output=None, build_dir='build', include_dirs=None, library_dirs=None, libraries=None, macros=None, cache=True) → module
Parameters:
  • name (str) – The module name (must be unique).
  • source (str) – the source code in C++.
Keyword Arguments:
 
  • sources (str) – Source files.
  • preprocess (str) – Source files that need cfly’s preprocessing.
  • output (str) – The output file. defaults to ‘{name}.pyd’.
  • build_dir (str) – The build directory. defaults to ‘build’.
  • include_dirs (list) – Additional include directories.
  • library_dirs (list) – Additional library directories.
  • libraries (list) – Additional libraries.
  • macros (list) – Predefined macros. (name, value) pairs.
  • cache (bool) – Enable cache.
Returns:

the compiled and imported module.

Examples

Hello World

hello_world.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from cfly import build_module

mymodule = build_module('mymodule', '''
    #include <Python.h>

    PyObject * meth_hello(PyObject * self, PyObject * args) {
        return PyUnicode_FromFormat("Hello World!");
    }
''')

print(mymodule.hello())

Arguments

arguments.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from cfly import build_module

mymodule = build_module('mymodule', '''
    #include <Python.h>

    PyObject * meth_mymethod(PyObject * self, PyObject * args) {
        const char * arg_str;
        int arg_int;

        if (!PyArg_ParseTuple(args, "si", &arg_str, &arg_int)) {
            return 0;
        }

        return PyUnicode_FromFormat("String: %s, Integer: %d", arg_str, arg_int);
    }
''')

print(mymodule.mymethod('Hello World!', 12345))

Sample Project

sample_project.py

1
2
3
4
5
6
7
8
9
from cfly import build_module

mymodule = build_module(
    'mymodule',
    sources=['examples/sample_project/something.cpp'],
    preprocess=['examples/sample_project/module.cpp'],
)

print(mymodule.get_x())

something.hpp

1
extern int x;

something.cpp

1
int x = 10;

module.cpp

1
2
3
4
5
6
7
#include "something.hpp"

#include <Python.h>

PyObject * meth_get_x(PyObject * self) {
    return PyLong_FromLong(x);
}

Indices and tables