In the work encountered such a call method, Java call c++, c++ call python, this call method is more troublesome. Today I will give you a general introduction. This article focuses on process, and you focus on process. Def say(word): print(word) return “hello” def say(word): print(word) return “hello”

Second, write Java code to generate c++ header files. Create the test folder and create a file called test. Java with the following contents: Package test; public class Test{ static{ System.loadLibrary(“test”); // create a c++ dynamic library named test, Windows test. DLL, Linux to generate a libtest.so dynamic library. }

Public native int test(String word); public static void main(String[] args){ Test t = new Test(); int a = t.test("this is a test"); System.out.println(a); }Copy the code

} generate c++ header files, this test environment Java version is java10, because this version does not support javah command, so we use javac -h instead. Run the following command in the same directory as the test folder: javac -h.. /test/ test. Java Folder structure is as follows:

The third step is to create a DLL project under VS, which is not detailed here. If you are not clear about it, you can baidu, which is relatively simple. Note that this project generates a dynamic library called test.dll. Create a file called test. CPP in this project with the following contents:

#include "stdafx.h" #include "Header.h" #include "Python.h" #include <iostream> #include <stdlib.h> #include "test_Test.h" using namespace std; int test(string word){ Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('D:/python_test/')"); PyObject* pModule = PyImport_ImportModule(" myPrint "); // Write the module name of your Python script here if (! << "[ERROR] Python get module failed." << endl; char c; cin >> c; return 0; } cout << "[INFO] Python get module succeed." << endl; PyObject* pv = PyObject_GetAttrString(pModule, "say"); if (! pv || ! PyCallable_Check(pv)) {cout << "[ERROR] Can't find funftion (test_add)" << endl; return 0; } cout << "[INFO] Get function (test_add) succeed." << endl; PyObject* args = PyTuple_New(1); const char *r = "this is a test"; PyTuple_SetItem(args, 0, Py_BuildValue("s", r)); PyObject *pReturn = PyEval_CallObject(pv, args); Py_Finalize(); char test; cin >> test; return 0; } JNIEXPORT jint JNICALL Java_test_Test_test (JNIEnv * env, jobject obj, jstring j_name){ string c_name = env->GetStringUTFChars(j_name, NULL); int res = test(c_name); return res; }Copy the code

Then go to the test folder and execute the Java command. java test/Test

Ok, the call between the three languages is as above. If you have any questions, please leave a comment. Behind will also continue to output some Java related articles, like friends can pay attention to it!