C ++ Boost Python (a simple example)

zhaozj2021-02-08  203

A simple example

Suppose we have the following C API to expose to Python:

#include

Namespace {// Avoid Cluttering The Global Namespace.

// a Couple of Simple C Functions That We want to express to python.

Std: string greet () {return "hello, world";

INT Square (int Number) {Return Number * Number;}

}

This is to expose the C source code for the API Getting_Started1 module to Python.

#include

Namespace python = boost :: python;

BOOST_PYTHON_MODULE_INIT (Getting_Started1)

{

Try

{

// Create An Object Representing this Extension Module.

Python :: Module_builder this_module ("getting_started1");

// Add regular functions to the module.

This_Module.def (Greet, "Greet");

this_module.def (Square, "Square");

}

Catch (...)

{

Python :: handle_exception (); // deal with the exception for python

}

}

It is! If we generate this shared library and put it in Python's search path, we can access these C functions in Python.

>>> Import getting_started1

>>> Print getting_started1.greet ()

Hello, World

>>> NUMBER = 11

>>> Print Number, '*', Number, '=', getting_started1.square (Number)

11 * 11 = 121

Next: Export class previous: Compare Up: Top

© David Abrahams 2001 All rights reserved. This document allows copy, use, modification, sale, and distribution, premise this copyright statement must appear on all copies. The provision of this document does not assume any direct or implicit guarantees, and does not make the statement that is suitable for any purpose.

Update Date: May 6, 2000

转载请注明原文地址:https://www.9cbs.com/read-2305.html

New Post(0)