alibaba / fastFFI

Apache License 2.0
121 stars 13 forks source link

C language encapsulation #41

Open yangyang233333 opened 1 year ago

yangyang233333 commented 1 year ago

Hello, may I ask if this library supports encapsulating the C language? For example, how can the following code be packaged using fastffi?

// func.h 
extern "C" {
extern int func(int **matrix, int n);
};

// func.cpp
int func (int ** matrix, int n) {
    // do xxx
    return sum;
}
yangyang233333 commented 1 year ago

@sighingnow

sighingnow commented 1 year ago

Try to wrap your C APIs into a dummy struct or class, then wrap it like other C++ classes (using static methods).

tianxiaogu commented 1 year ago

You may use FFILibrary designed for functions defined in a namespace. For any C function, it could be viewed as defined in the global empty namespace. Here is an example:

@FFIGen
@FFILibrary(value = "cmath", namespace = "")
@CXXHead("math.h")
public interface C {
    double fabs(double v);
    double pow(double x, double y);
}

Field value in the @FFILibrary is simply a key used to register an instance of the FFILibrary in FFITypeFactory.

To use the interface C, we need to obtain an instance of the FFILibrary via FFITypeFactory.

import com.alibaba.fastffi.FFITypeFactory;

public class Main {
    public static void main(String[]args) {
        C clib = FFITypeFactory.getLibrary(C.class);
        double a = 1.234;
        double b = 2.345;
        double c = -3.456;
        System.out.println(clib.fabs(a));
        System.out.println(clib.fabs(b));
        System.out.println(clib.fabs(c));
        System.out.println(clib.pow(a, b));
        System.out.println(Math.pow(a, b));
    }
}
yangyang233333 commented 1 year ago

Thank you very much for your answer. I have another small question: How should I write Java side code for the following types of pointers?

extern "C" {
typedef struct my_struct my_struct_t;
void func(my_struct_t* ptr, int* val);
}

Looking forward to your reply.

siya186 commented 1 year ago

In Java, there's no direct equivalent to pointers like in C, but you can achieve similar functionality using Java's object references and native method calls. @yangyang233333