使用UnmanagedExports从c#回调到java

时间:2016-04-01 05:38:18

标签: java c# java-native-interface

我需要的是java能够将函数传递给c#,c#可以在执行后回调。我该怎么做?

以下是来自Java和c#类的两个示例代码段。这适用于简单地将字符串从java传递到c#。

示例c#代码

using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace Hello
{    
    public class Hello
    {
        public delegate void VoidStringDelegate(string str);

        [DllExport]
        public static unsafe string sayHello(string name)
        {
            return string.Format("Hello {0} from c#", name);
        }

        [DllExport]
        public static unsafe void processAndCallback(VoidStringDelegate callback)
        {
            callback("Started");
            Thread.Sleep(5000);
            callback("Done");
        }       

    }
}

示例Java代码

import com.sun.jna.Native;
import com.sun.jna.Library;
import java.lang.reflect.Method;

public class Hello {

    public static class CallbackWrap 
    {   
        public void Callback(String msg) 
        {
            System.out.println("Call back: " + msg);
        }   
    };

    public interface IHello extends Library
    {
       public String sayHello(String tStr);
       public String processAndCallback(Method callback);      
    };  

    public static void main(String[] args) {
        System.out.println("Hello");        
        IHello iHello = (IHello)Native.loadLibrary("Hello", IHello.class);//call JNA
        System.out.println("Returned: " + iHello.sayHello("Java"));

        Class[] parameterTypes = new Class[1];
        parameterTypes[0] = String.class;
        Method method1 = CallbackWrap.class.getMethod("CallbackWrap::Callback", parameterTypes);

        iHello.processAndCallback(method1);       
    }



}

0 个答案:

没有答案