yglukhov / nimpy

Nim - Python bridge
MIT License
1.48k stars 60 forks source link

keeping long lived objects alive from python #281

Closed root-11 closed 1 year ago

root-11 commented 1 year ago

How to keep long-lived objects alive from python?

Most examples I've seen use nimpy in a functional capacity such as in this example, but is it possible to use nimpy - just like sqlite - where a C object is instantiated once and kept alive for interaction in further subsequent calls?

In the example below db is an in-memory object that is kept alive for subsequent transactions:

db = sqlite3.connect("file::memory:?cache=shared")
with db:
    cur = db.cursor()
    cur.execute(*args)

In numpy the same wrapping occurs:

import numpy as np
numbers = np.zeros(2)  # c call.
numbers[0] = 1  # call to c object to update value.

I would be grateful for a brief example on how this may be done?

Something as simple as this would do:

nimlist = example()  # loads integers 1..5 as C objects. These are never returned to python.
print( nim_index(3) )  # calls nimlist to index and returns a single value.

Kind regards root-11

root-11 commented 1 year ago

I believe this is a part of the game: pybind11 keeping objects alive but I am clueless whether nimpy support this.

yglukhov commented 1 year ago

Most ref objects will do what you want. Just return your ref object from a nim function, then pass it to other nim functions.

Also you can try exporting nim classes