84

CのPythonモジュールで定義されているカスタム関数を呼び出したいのですが、それを行うための予備的なコードがいくつかありますが、出力をstdoutに出力するだけです。

mytest.py

import math

def myabs(x):
    return math.fabs(x)

test.cpp

#include <Python.h>

int main() {
    Py_Initialize();
    PyRun_SimpleString("import sys; sys.path.append('.')");
    PyRun_SimpleString("import mytest;");
    PyRun_SimpleString("print mytest.myabs(2.0)");
    Py_Finalize();

    return 0;
}

戻り値をCに抽出し、Cで使用するにはどうすればよいdoubleですか?

4

10 に答える 10

97

前に説明したように、PyRun_SimpleStringを使用することは悪い考えのようです。

C-API( http://docs.python.org/c-api/ )が提供するメソッドを確実に使用する必要があります。

イントロダクションを読むことは、それがどのように機能するかを理解するために最初に行うことです。

まず、CAPIの基本オブジェクトであるPyObjectについて学習する必要があります。あらゆる種類のPython基本型(string、float、int、...)を表すことができます。

たとえば、Python文字列をchar *に変換したり、PyFloatをdoubleに変換したりするための多くの関数が存在します。

まず、モジュールをインポートします。

PyObject* myModuleString = PyString_FromString((char*)"mytest");
PyObject* myModule = PyImport_Import(myModuleString);

次に、関数への参照を取得します。

PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"myabs");
PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0));

次に、結果を取得します。

PyObject* myResult = PyObject_CallObject(myFunction, args)

そして、ダブルに戻ります:

double result = PyFloat_AsDouble(myResult);

明らかにエラーをチェックする必要があります(Mark Tolonenによるリンクを参照)。

ご不明な点がございましたら、お気軽にお問い合わせください。幸運を。

于 2010-07-22T15:33:17.330 に答える
31

これは、Pythonコードに文字列を送信して値を返すために(さまざまなオンラインソースを使用して)作成したサンプルコードです。

これがCコードですcall_function.c

#include <Python.h>
#include <stdlib.h>
int main()
{
   // Set PYTHONPATH TO working directory
   setenv("PYTHONPATH",".",1);

   PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;


   // Initialize the Python Interpreter
   Py_Initialize();


   // Build the name object
   pName = PyString_FromString((char*)"arbName");

   // Load the module object
   pModule = PyImport_Import(pName);


   // pDict is a borrowed reference 
   pDict = PyModule_GetDict(pModule);


   // pFunc is also a borrowed reference 
   pFunc = PyDict_GetItemString(pDict, (char*)"someFunction");

   if (PyCallable_Check(pFunc))
   {
       pValue=Py_BuildValue("(z)",(char*)"something");
       PyErr_Print();
       printf("Let's give this a shot!\n");
       presult=PyObject_CallObject(pFunc,pValue);
       PyErr_Print();
   } else 
   {
       PyErr_Print();
   }
   printf("Result is %d\n",PyInt_AsLong(presult));
   Py_DECREF(pValue);

   // Clean up
   Py_DECREF(pModule);
   Py_DECREF(pName);

   // Finish the Python Interpreter
   Py_Finalize();


    return 0;
}

これがファイル内のPythonコードですarbName.py

 def someFunction(text):
    print 'You passed this Python program '+text+' from C! Congratulations!'
    return 12345

このコマンドを使用してgcc call_function.c -I/usr/include/python2.6 -lpython2.6 ; ./a.outこのプロセスを実行します。私はRedHatを使用しています。PyErr_Print();を使用することをお勧めします。エラーチェック用。

于 2014-07-10T22:21:13.033 に答える
10

Python関数を呼び出して結果を取得する完全な例は、http: //docs.python.org/release/2.6.5/extending/embedding.html#pure-embeddingにあります。

#include <Python.h>

int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyString_FromString(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}
于 2010-07-20T03:18:48.117 に答える
5

他の回答のように余分な.pyファイルを防ぐために、:__main__への最初の呼び出しによって作成されたモジュールを取得するだけです。PyRun_SimpleString

PyObject *moduleMainString = PyString_FromString("__main__");
PyObject *moduleMain = PyImport_Import(moduleMainString);

PyRun_SimpleString(
    "def mul(a, b):                                 \n"\
    "   return a * b                                \n"\
);

PyObject *func = PyObject_GetAttrString(moduleMain, "mul");
PyObject *args = PyTuple_Pack(2, PyFloat_FromDouble(3.0), PyFloat_FromDouble(4.0));

PyObject *result = PyObject_CallObject(func, args);

printf("mul(3,4): %.2f\n", PyFloat_AsDouble(result)); // 12
于 2015-08-03T21:30:56.113 に答える
1

どういうわけかpythonメソッドを抽出し、それをで実行する必要がありPyObject_CallObject()ます。これを行うには、 Pythonチュートリアルの拡張と埋め込みの例のように、関数を設定する方法をPythonに提供できます。

于 2010-07-20T02:24:04.120 に答える
1

戻り値を変数に割り当てる場合は、PyEval_GetGlobals()やPyDict_GetItemString()などを使用してPyObjectを取得できます。そこから、PyNumber_Floatは必要な値を取得できます。

API全体を参照することをお勧めします。使用可能なさまざまなメソッドを見ると、特定のことが明らかになります。これまでに説明したメソッドよりも優れたメソッドがある可能性があります。

于 2010-07-20T10:07:21.293 に答える
1

BOOSTを使用してPythonをC++に埋め込みました[この動作するCモジュールが役立つはずです]

#include <boost/python.hpp>

void main()
{
using namespace boost::python;
 Py_Initialize();
 PyObject* filename = PyString_FromString((char*)"memory_leak_test");
     PyObject* imp = PyImport_Import(filename);
     PyObject* func = PyObject_GetAttrString(imp,(char*)"begin");
     PyObject* args = PyTuple_Pack(1,PyString_FromString("CacheSetup"));
     PyObject* retured_value = PyObject_CallObject(func, args); // if you have arg
     double retured_value = PyFloat_AsDouble(myResult);
 std::cout << result << std::endl;
 Py_Finalize();
}
于 2014-06-26T20:54:05.377 に答える
0

これがあなたの質問に対する簡単で直接的な答えです:

    #include <iostream>
    #include <Python.h>
    using namespace std;
    int main()
    {
    const char *scriptDirectoryName = "/yourDir";
    Py_Initialize();
    PyObject *sysPath = PySys_GetObject("path");
    PyObject *path = PyString_FromString(scriptDirectoryName);
    int result = PyList_Insert(sysPath, 0, path);
    PyObject *pModule = PyImport_ImportModule("mytest");

    PyObject* myFunction = PyObject_GetAttrString(pModule,(char*)"myabs");
    PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(-2.0));


    PyObject* myResult = PyObject_CallObject(myFunction, args);
    double getResult = PyFloat_AsDouble(myResult);
    return 0;
    }
于 2020-02-28T07:44:36.990 に答える
0

これは、Python 3でも動作する最小限の実行可能バージョンです(Python 2.7および3.9でテスト済み)。

ドキュメントへのリンクはコメントに含まれていますが、すべてhttps://docs.python.org/3/c-api/からアクセスできます。

#include <Python.h>
#include <stdio.h>

int main()
{
    // Initialize the Python Interpreter
    Py_Initialize();

    // see https://docs.python.org/3/c-api/structures.html
    // NULL objects are special and Py_CLEAR knows this
    PyObject *module = NULL, *result = NULL;

    // https://docs.python.org/3/c-api/import.html
    module = PyImport_ImportModule("mytest");
    if (!module) {
        // Python generally uses exceptions to indicate an error state which
        // gets flagged in the C-API (a NULL pointer in this case) indicating
        // "something" failed. the PyErr_* API should be used to get more
        // details
        goto done;
    }

    // see https://docs.python.org/3/c-api/call.html#c.PyObject_CallMethod
    // and https://docs.python.org/3/c-api/arg.html#building-values
    result = PyObject_CallMethod(module, "myabs", "f", 3.14);
    if (!result) {
        goto done;
    }

    // make sure we got our number back
    if (PyFloat_Check(result)) {
        printf("Successfully got a float: %f\n", PyFloat_AsDouble(result));
    } else {
        printf("Successfully got something unexpected!\n");
    }

  done:
    // see https://docs.python.org/3/c-api/exceptions.html
    PyErr_Print();

    // see https://docs.python.org/3/c-api/refcounting.html
    Py_CLEAR(result);
    Py_CLEAR(module);

    // Optionally release Python Interpreter
    Py_Finalize();

    return 0;
}

これは、OPのPythonコードmytest.py、またはこれに相当する1行を使用します。

from math import fabs as myabs

ビルドはOS/Pythonバージョン固有になりますが、以下は私にとってはうまくいきます:

cc -o test -I/usr/include/python3.9 /usr/lib/libpython3.9.so test.c
于 2021-11-03T00:12:58.093 に答える
0

他の人がすでに述べたように、これはPythonのドキュメントで回答されています。ただし、私はPythonから来ており、C / C ++の使用経験があまりないため、Python 3での実行に問題がありました。他の投稿に時間を費やした後、Pythonドキュメントを実行するための完全な実例を次に示します。スタックオーバーフローの:

ファイルc_function.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();

    // I had to add the following two lines to make it work
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");

    pName = PyUnicode_DecodeFSDefault(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    if (Py_FinalizeEx() < 0) {
        return 120;
    }
    return 0;
}

ファイルmultiply.py

def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c

コンパイルしてリンクする必要があります。これは、次のコマンドで実行できます。

gcc c_function.c -c $(python3.6-config --cflags) -fPIC

に続く

gcc c_function.o $(python3.6-config --ldflags) -o call

Python3.6の例の場合。その後、Pythonドキュメントの例は次の方法で実行できます。

./call multiply multiply 3 2
于 2022-01-20T16:50:21.953 に答える