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

Passing a function pointer + env to a class constructor fails but works if applied directly #14920

Closed
deech opened this issue Jul 6, 2020 · 0 comments

Comments

@deech
Copy link
Contributor

deech commented Jul 6, 2020

When I create a C++ class that emulates a closure with function pointer and environment members and a member function that runs them I get a segfault. If I directly apply the closure in a standalone function it succeeds.

Example

{.emit: """/*TYPESECTION*/
class ClosureClass
{
  void (*c)(void*);
  void* env;
  public:
    ClosureClass(void (*c)(void*), void* env) { c = c; env=env; }
    void run() { (*c)(env); }
};
void apply(void(*c)(void*), void* env) { (*c)(env); }
""".};

type ClosureClass {.importcpp: "ClosureClass".} = object
type Closure = proc () {.nimcall.}

proc makeClosure(): proc () =
  let s = "from closure scope"
  return (proc () = echo s)

proc constructClosureClass(p:Closure,env:pointer):ptr ClosureClass {.importcpp: "new ClosureClass(@)".}
let f = makeClosure()
var c = constructClosureClass(cast[Closure](rawProc f), rawEnv f)

# works fine
proc apply(p:Closure,env:pointer) {.importcpp: "apply(@)".}
apply(cast[Closure](rawProc f), rawEnv f)

# segfaults
proc run(this:ClosureClass) {.importcpp:"#.run()".}
run(c[])

Current Output

from closure scope
Traceback (most recent call last)
/home/deech/Nim/cppclosure.nim(28) cppclosure
SIGSEGV: Illegal storage access. (Attempt to read from nil?)

Expected Output

from closure scope
from closure scope
$ nim -v
Nim Compiler Version 1.3.5 [Linux: amd64]
Compiled at 2020-07-06
Copyright (c) 2006-2020 by Andreas Rumpf

git hash: a754160d654f03584088412f51b153ae6a170adb
active boot switches: -d:release
@deech deech closed this as completed Jul 7, 2020
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

1 participant