1+ #include < pybind11/pybind11.h>
2+ #include < pybind11/stl.h>
3+ #include < vector>
4+ #include < iostream>
5+ #include < dlfcn.h> // For dlopen and dlsym
6+ #include < hello-world.h>
7+
8+
9+
10+ // ----------------
11+ // Regular C++ code
12+ // ----------------
13+
14+ // multiply all entries by 2.0
15+ // input: std::vector ([...]) (read only)
16+ // output: std::vector ([...]) (new copy)
17+ std::vector<double > modify (const std::vector<double >& input)
18+ {
19+ std::vector<double > output;
20+
21+ std::transform (
22+ input.begin (),
23+ input.end (),
24+ std::back_inserter (output),
25+ [](double x) -> double { return 2 .*x; }
26+ );
27+
28+ // N.B. this is equivalent to (but there are also other ways to do the same)
29+ //
30+ // std::vector<double> output(input.size());
31+ //
32+ // for ( size_t i = 0 ; i < input.size() ; ++i )
33+ // output[i] = 2. * input[i];
34+
35+ return output;
36+ }
37+
38+ // ----------------
39+ // Python interface
40+ // ----------------
41+
42+ namespace py = pybind11;
43+
44+ // Load and call the GraalVM native library
45+ const char * call_graalvm_method (char * input)
46+ {
47+ graal_isolate_t *isolate = NULL ;
48+ graal_isolatethread_t *thread = NULL ;
49+
50+ if (graal_create_isolate (NULL , &isolate, &thread) != 0 ) {
51+ return " initialization error\n " ;
52+ }
53+
54+ // Call the function
55+ const char * result = greet (thread, input);
56+
57+ // Duplicate the string to ensure the memory is managed independently
58+ size_t len = strlen (result);
59+ char * duplicated_result = new char [len + 1 ];
60+ strncpy (duplicated_result, result, len);
61+ duplicated_result[len] = ' \0 ' ; // Ensure null termination
62+
63+ graal_tear_down_isolate (thread);
64+
65+ return duplicated_result;
66+ }
67+
68+
69+ PYBIND11_MODULE (example,m)
70+ {
71+ m.doc () = " pybind11 example plugin" ;
72+
73+ m.def (" modify" , &modify, " Multiply all entries of a list by 2.0" );
74+
75+ // GraalVM native function exposed to Python
76+ m.def (" call_graalvm" , &call_graalvm_method, " Call a GraalVM native method" );
77+ }
78+
79+ int main () {
80+ // Example input string
81+ char input[] = " World" ;
82+
83+ // Call the GraalVM native method
84+ const char * result = call_graalvm_method (input);
85+
86+ // Check if the result is valid and print the result
87+ if (result) {
88+ std::cout << " GraalVM result: " << result << std::endl;
89+ } else {
90+ std::cerr << " Error calling GraalVM method." << std::endl;
91+ }
92+
93+ return 0 ;
94+ }
0 commit comments