How to pass wide strings in Java calling the MessageBoxW function in user32 lib

微笑、不失礼 提交于 2021-01-28 04:34:05

问题


I am currently struggling to use the function MessageBoxW in Java. I have managed to successfully call the user32 library and use the MessageBoxA function. Here's my code below:

package messagebox;

import com.sun.jna.Library;
import com.sun.jna.Native;

public class MessageBox 
{
    public interface user32 extends Library
    {
        public int MessageBoxA(int something, String text, String caption, int flags);
    }

    public static void main(String[] args) 
    {
        System.out.println("Program starting... Library loading... ");
        user32 lib = (user32) Native.loadLibrary("user32", user32.class);
        System.out.println("Presenting Message Box ...");
        lib.MessageBoxA(0,"MessageBox success!!!","Attention",0);
    }
}

I've looked around and could not find any conclusive answers but something tells me that I need much more sophisticated coding to tackle this problem. Any help with this would be much appreciated.


回答1:


Looking at the documentation (confirming my suspicions). Java strings, which by default have 16 bit characters, are converted to 8 bit character strings so they fit the C char* type.

But what happens if you actually want to print wide (16 bit) characters on the C side? The ascii values that were obtained from converting the java string are interpreted as unicode values, so they don't match what you typed.

The documentation mentions using the WString type to avoid the conversion to ascii.

You should change the method signature to:

int MessageBoxW(int something, WString text, WString caption, int flags);

And then call it with:

lib.MessageBoxW(0, new WString("MessageBox success!!!"), new WString("Attention"), 0);

Tested with jna-4.2.2



来源:https://stackoverflow.com/questions/37002326/how-to-pass-wide-strings-in-java-calling-the-messageboxw-function-in-user32-lib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!