yglukhov / nimpy

Nim - Python bridge
MIT License
1.45k stars 62 forks source link

Export nim-object-proc link during call from nim #180

Open inv2004 opened 3 years ago

inv2004 commented 3 years ago

Hello, Is it possible to export object type and its function into python, but without using precompiled module?

Here is an example, which works, but I put comment there:

type
  NimObj = ref object
    x: int

proc fn1(o: NimObj, x: int) =
  o.x.inc(x)

writeFile("t.py", """
class MyClass:
    def method1(self, obj, f):  # expected: method1(self, obj):
        f(obj, 1)                         # expected: obj.inc(1)
""")
let obj = NimObj()

discard pyImport("sys").path.append(".")
let t = pyImport("t")
let c = t.MyClass()
discard c.method1(obj, fn1)
discard c.method1(obj, fn1)

echo obj.x

removeFile("t.py")

My next idea is to export nim-class somehow, and in python use the following:

class MyClass(NimClass):
    def method1(self):
        super().inc(1)
inv2004 commented 3 years ago

Ok, looks like I found the same issue, so the question is:

1) Is there any option to expose proc without precompiled .so or .pyd? 2) Any future plans to support expose classes?

Thank you,

inv2004 commented 3 years ago
  1. The same question, but about expose struct(object) without methods
yglukhov commented 3 years ago
  1. I don't understand the question
  2. Classes were introduced in #210
  3. Not yet
yglukhov commented 2 years ago
  1. I think I understood the question. Here's the solution:
    
    import nimpy

type NimObj = ref object x: int

proc fn1(o: NimObj, x: int) = o.x.inc(x)

pyGlobals()["fn1"] = fn1 # Add function to python globals

discard pyBuiltinsModule().exec """ class MyClass: def method1(self, obj): fn1(obj, 1) """

let obj = NimObj()

let MyClass = pyGlobals()["MyClass"].to(proc():PyObject) # Get MyClass constructor from globals let c = MyClass() discard c.method1(obj) discard c.method1(obj)

echo obj.x