1. 返回字符串类型
c/c++代码
- 全局变量
char retp[1024];
const char* getStr1(int a, int b){
memset(retp, 0, 1024);
char outstr[256];
memset(outstr, 0, 256);
if (outstr != 0){
sprintf_s(outstr, "汉字out DLL汉字: %d + %d==%d\n", a, b, (a + b));
}
strcpy_s(retp, outstr);
return retp;
}
- malloc函数分配空间
const char* getStr2(int a, int b){
char* retp = (char*)malloc(1024);
memset(retp, 0, 1024);
char outstr[256];
memset(outstr, 0, 256);
if (outstr != 0){
sprintf_s(outstr, "汉字out DLL汉字: %d + %d==%d\n", a, b, (a + b));
//printf("%s",outstr);
}
strcpy_s(retp, strlen(outstr) + 1, outstr);
return retp;
}
java代码
package com.jnademo;
import com.sun.jna.Library;
import com.sun.jna.Native;
public class JnaTest {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.load("E:\\dllws\\jnaTest\\x64\\Debug\\jnaTest.dll",
CLibrary.class);
String getStr1(int a, int b);
String getStr2(int a, int b);
}
public static void main(String[] args) {
System.setProperty("jna.encoding","GBK");
System.out.println(CLibrary.INSTANCE.getStr1(1, 3));
System.out.println(CLibrary.INSTANCE.getStr2(2, 3));
}
}
要注意添加System.setProperty("jna.encoding","GBK");
否则会出现乱码。具体规则
- c++ char* GBK编码时
System.setProperty("jna.encoding", "GBK");
- c++ char* UTF8编码时
System.setProperty("jna.encoding", "UTF-8");
另外,其实还有个更简单的办法,JNA提供了一个宽字符字符串WString,当然c++接口参数类型要使用wchar_t*
,这样WString就可以无缝转wchar_t*
了,不用做任何修改,也绝对不会乱码。
C/C++接收字符串类型
C/C++代码
bool JavaStr(char* szText, int textLen) {
if (szText == NULL || textLen <= 0) {
return false;
}
std::string strText(szText, textLen);
//OutputDebugStringA("JavaStr:");
//OutputDebugStringA(strText.c_str());
cout << strText.c_str() << endl;
return true;
}
java代码
package com.jnademo;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.Library;
import com.sun.jna.Native;
public class TestStructDemo {
public interface TestStruct extends Library {
TestStruct INSTANCE = (TestStruct) Native.load("E:\\dllws\\jnaTest\\x64\\Debug\\jnaTest.dll",
TestStruct.class);
public boolean JavaStr(String str, int strLen); // 使用String传参数,中文会参数乱码
public boolean JavaStr(byte[] str, int strLen); // 使用byte[]传参数,中文正常
}
public static void main(String[] args) throws UnsupportedEncodingException {
//https://blog.51cto.com/softo/6009271
String utf8Str = "UTF8转成GBK";
String gbkStr = new String(utf8Str.getBytes("UTF-8"), "GBK"); // UTF8转成GBK
byte[] gbkBytes = utf8Str.getBytes("UTF-8");
TestStruct.INSTANCE.JavaStr(gbkStr, gbkStr.length()); // 传字符串C++接收时中文是乱码
TestStruct.INSTANCE.JavaStr(gbkBytes, gbkBytes.length); // 传字节数组C++接收中文正常
}
}
参考:
https://blog.csdn.net/redchairman/article/details/108438202
https://blog.csdn.net/houmingyang/article/details/127071298
标签:String,int,jna,char,类型,JNA,outstr,字符串,public
From: https://www.cnblogs.com/happyhuangjinjin/p/17220049.html