Bläddra i källkod

support dll load

blueloveTH 1 år sedan
förälder
incheckning
7964cc1af6
5 ändrade filer med 62 tillägg och 6 borttagningar
  1. 1 3
      .gitignore
  2. 6 0
      build_dll.sh
  3. 36 0
      src/interpreter/dll.c
  4. 4 3
      src/public/modules.c
  5. 15 0
      src2/hello.c

+ 1 - 3
.gitignore

@@ -26,9 +26,7 @@ APPS
 build
 
 main
-pocketpy.dSYM
-libpocketpy.dylib.dSYM/
-main.dSYM/
+*.dSYM
 
 docs/references.md
 

+ 6 - 0
build_dll.sh

@@ -0,0 +1,6 @@
+set -e
+
+FLAGS="-std=c11 -Iinclude -O0 -Wfatal-errors -g -DDEBUG -DPK_ENABLE_OS=1"
+
+clang $FLAGS -shared -fPIC src2/hello.c -o libhello.dylib -undefined dynamic_lookup
+

+ 36 - 0
src/interpreter/dll.c

@@ -0,0 +1,36 @@
+#include "pocketpy/pocketpy.h"
+
+#if PK_IS_DESKTOP_PLATFORM
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <dlfcn.h>
+#endif
+
+typedef bool (*py_module_initialize_t)() PY_RAISE PY_RETURN;
+
+int load_module_from_dll_desktop_only(const char* path) PY_RAISE PY_RETURN {
+    const char* f_init_name = "py_module_initialize";
+#ifdef _WIN32
+    HMODULE dll = LoadLibraryA(path);
+    if(dll == NULL) return 0;
+    py_module_initialize_t f_init = (py_module_initialize_t)GetProcAddress(dll, init_func);
+#else
+    void* dll = dlopen(path, RTLD_LAZY);
+    if(dll == NULL) return 0;
+    py_module_initialize_t f_init = (py_module_initialize_t)dlsym(dll, f_init_name);
+#endif
+    if(f_init == NULL) return 0;
+    bool success = f_init();
+    if(!success) return -1;
+    return 1;
+}
+
+#else
+
+int load_module_from_dll_desktop_only(const char* path) PY_RAISE PY_RETURN {
+    return 0;
+}
+
+#endif

+ 4 - 3
src/public/modules.c

@@ -63,9 +63,9 @@ py_Ref py_newmodule(const char* path) {
     return py_getmodule(path);
 }
 
-int py_import(const char* path_cstr) {
-    // printf("importing %s\n", path_cstr);
+int load_module_from_dll_desktop_only(const char* path) PY_RAISE PY_RETURN;
 
+int py_import(const char* path_cstr) {
     VM* vm = pk_current_vm;
     c11_sv path = {path_cstr, strlen(path_cstr)};
     if(path.size == 0) return ValueError("empty module name");
@@ -142,7 +142,8 @@ int py_import(const char* path_cstr) {
 
     c11_string__delete(filename);
     c11_string__delete(slashed_path);
-    return 0;
+    // not found
+    return load_module_from_dll_desktop_only(path_cstr);
 
 __SUCCESS:
     do {

+ 15 - 0
src2/hello.c

@@ -0,0 +1,15 @@
+#include "pocketpy.h"
+
+static bool hello_add(int argc, py_Ref argv){
+    PY_CHECK_ARGC(2);
+    return py_binaryadd(py_arg(0), py_arg(1));
+}
+
+bool py_module_initialize(){
+    py_GlobalRef mod = py_newmodule("hello");
+
+    py_bindfunc(mod, "add", hello_add);
+
+    py_assign(py_retval(), mod);
+    return true;
+}