来自c ++应用程序的Java com.sun.jna回调函数

时间:2012-11-15 23:35:45

标签: java callback jna

我有一个用C ++编写的DLL,我无法改变。它具有以下暴露功能

// c++ 
DllExport unsigned int ProcessMessage( char * in_message, USHORT in_message_length, char * connectionString, bool ( SendMessage)( char * connectionString, BYTE * payload, USHORT iPayloadSize )  );

我有一个需要调用此DLL函数的Java应用程序。我目前正在使用java库com.sun.jna

// Java 
public class main {
    public interface CBlargAPI extends Library {
        interface sendMessage_t extends Callback {
            boolean invoke(String connectionString, Pointer payload, short iPayloadSize );
        }
        int ProcessMessage( byte[] in_message, short in_message_length, String connectionString, sendMessage_t SendMessage ) ; 
    }
    public static void main(String[] args) throws Exception 
    {
        // Override function thingy (#A) 
        CBlarg.sendMessage_t sendMessage_fn  = new CBlarg.sendMessage_t() {
            @Override
            public boolean invoke(String connectionString, Pointer payload, short iPayloadSize) {
                System.out.println("sendMessage_t: " )  ;
                return false; 
                }
            };         
        }
        CBlargAPI.INSTANCE.ProcessMessage( receivePacket.getData(), (short) receivePacket.getLength(), connectionString, sendMessage_fn ); 
    }

    // static member function (#B) 
    public static boolean SendUDPMessage( String connectionString, Pointer payload, short length )  {    
        // ToDo: I want to use this one. 
    }
}

目前这适用于override function thingy (#A),但我想改用static member function (#B)。我尝试过一些没有成功的事情,比如

// Errors with "cannot find symbol, symbol: class SendUDPMessage, location: class main" 
CBACnetAPI.sendMessage_t sendMessage_fn  = new main.SendUDPMessage();

我是一名c ++程序员,很少接触java

我的问题是:

  • 如何将静态成员函数SendUDPMessage()称为回调而不是Override function thingy (#A)

1 个答案:

答案 0 :(得分:1)

您必须override function thingy (#A)拨打static member function(#B)。 Java没有函数指针,因此您需要一个接口对象来实现此目的。

为什么你需要在#A上做#B?