Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
inv2004 opened this issue Nov 24, 2020 · 4 comments
Open

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

inv2004 opened this issue Nov 24, 2020 · 4 comments

Comments

@inv2004
Copy link

inv2004 commented Nov 24, 2020

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
Copy link
Author

inv2004 commented Nov 24, 2020

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
Copy link
Author

inv2004 commented Nov 25, 2020

  1. The same question, but about expose struct(object) without methods

@yglukhov
Copy link
Owner

  1. I don't understand the question
  2. Classes were introduced in Exported types basic impl. Closes #115, #146, #209 #210
  3. Not yet

@yglukhov
Copy link
Owner

  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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants