dart-archive / ffi

Utilities for working with Foreign Function Interface (FFI) code
https://pub.dev/packages/ffi
BSD 3-Clause "New" or "Revised" License
156 stars 32 forks source link

Can I get a class(object) from function return value? #200

Closed millie-molly closed 1 year ago

millie-molly commented 1 year ago

I have initialize function that retrun a class ( object ). I am trying to get a return value as a dynamic how can I make it?

here is an example.

define function typedef CreateClassFileC = Pointer Function(); // cannot define cast type. like Pointer typedef CreateClassFileDart = Pointer Function();

Pointer createClass() { final createClass = dll.lookup<NativeFunction>('Dll_createClass'); final createClassFunc = createClass.asFunction(); final resp = createClassFunc(); return resp; }

call function Pointer testClass= createClass(); OR dynamic testClass= createClass();

now, I am trying to call a class's function. testClass.callFunc(); // how to call dynamic funtion's method? I got no instance error. // I got error "NoSuchMethodError: Class 'Pointer' has no instance getter 'ref'(callFunc)." // or was called on null error.

Or can you tell me how to get return value as a class ( object ) from a function?

dcharkes commented 1 year ago

.ref is an extension method, not an instance method: https://api.dart.dev/stable/3.0.5/dart-ffi/StructPointer/ref.html

Even methods that are instance methods in dart:ffi are often prohibited to be used from dynamic. The reason is that we need to "see" the dart:ffi uses at compile time because it uses a special compilation.

Why do you want to use dynamic? Why not use final testClass = createClass() (or var testClass = ...) and have static typing without having to write the type?

millie-molly commented 1 year ago

I found same issue 123

My understanding is that class is not part of ABI, so change class to struct from header file.

Is it right?

BTW, static variable ( using final ) returns same error.

dcharkes commented 1 year ago

I found same issue 123

This is a different issue from what you were asking earlier, correct?

Earlier you were asking about using dynamic in Dart, and now you are asking about C++ classes with FFI.

My understanding is that class is not part of ABI, so change class to struct from header file.

Is it right?

Correct, structs are a C concept.

BTW, static variable ( using final ) returns same error.

The same as dynamic? That is very weird because with final it should have the correct type and be able to resolve .ref to the extension method.

millie-molly commented 1 year ago

Alright, I try to change it. And since ### final cannot find a correct type, I think return the same error. Anyway, thanks to help me I appreciate it.