[C++-sig] (Stefan Seefeld)(Nat Goodspeed) pass function pointerto c

Nat Goodspeed ngoodspeed at solidworks.com
Sat Oct 7 15:53:24 CEST 2006


________________________________________
From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On
Behalf Of Qinfeng(Javen) Shi 
Sent: Saturday, October 07, 2006 4:07 AM
To: c++-sig at python.org
Subject: Re: [C++-sig] (Stefan Seefeld)(Nat Goodspeed) pass function
pointerto c

The reason why I don't pass a string parameter then assign a function
pointer inside the process() is that,
I want to provide a extendable interface. The goal is that user can
provide any new operation function without rewriting process().
For instance, if a user write a new operation function called
"multiply"(any name but I could't know what name he would like to give),
he can still call process(arg1,..., multiply). One day another user
write another operation function called "vectorproduct", he can also
call process(arg1,...,vectorproduct). 

[Nat] Okay, that's a good reason not to do it the way I originally
suggested. 

If I do it in Stefan's way, every time when user provide a new operation
function, the process() has to be rewriten. User may not want to rewrite
process() code every time, and furthermore the source code of process()
is not always provided for users. 

[Nat] Here's where the disconnect lies. I must respectfully disagree
with your statement that process() must be rewritten to extend the set
of operation functions.

I think it would go something like this (not compiled, silly syntax
errors likely):

----- C++ code defining ProcessModule -----

// Candidate functions for 'op'
float add(float a, float b){
    return a+b;
}

float minus(float a, float b){
    return a-b;
}

// op
boost::python::object op;

// Was choose_op just for your test program, if process accepts
// arg_op?
void choose_op(boost::python::object method)
{
    op = method;
}

// process
void process(arg1,..., boost::python::object arg_op){
    ...
    op = arg_op;
    ...
    float a = 5;
    float b = 3;
    float result = op(a, b);
    ...
}

// ... publish add, minus, choose_op, process as usual ...

----- Python code -----

import ProcessModule

process(..., ProcessModule.add)

process(..., ProcessModule.minus)

// You can define new operation functions in ProcessModule or elsewhere.
// You can even define them in Python:

def multiply(a, b):
    return a * b

process(..., multiply)




More information about the Cplusplus-sig mailing list