想用java调用c#dll,各位,本来好好的,不知道为啥又不行了,一直报Invalid memory access,
不知道跟.net Net Framework 有没有关系,因为之前的c#dll是4.0的,后面改成4.7.2了 。各位兄弟姐妹救命!
java代码:
static{
//修改编码
System.setProperty("jna.encoding", "GBK");
}
@Test
void contextLoads()throws IOException {
System.out.println(CLibrary.INSTANCE.GetOrder("123", "232", "13"));
System.out.println(CLibrary.INSTANCE.GetParam(url, FactoryCode, "13","12","20","10","123"));
}
public interface CLibrary extends Library {
// DLL文件默认路径为项目根目录,若DLL文件存放在项目外,请使用绝对路径 C:\Users\zhi\Desktop\dll\
CLibrary INSTANCE = (CLibrary) Native.load( "C:\\Users\\zhi\\Desktop\\dll\\demo", CLibrary.class);
// 声明将要调用的DLL中的方法(可以是多个方法)
String GetOrder(String format, String PASSWORD, String SHA1);
String GetParam(String serverurl, String code, String line,
String specCode, String device, String proudct, String semproudct);
}
c++:
#ifdef MYLIBAPI
#else
#define MYLIBAPI extern "C" __declspec(dllimport)
#endif
MYLIBAPI char* GetOrder(char* ServerUrl, char* FactoryCode, char* LineCode); //添加函数声明
MYLIBAPI char* GetParam(char* ServerUrl, char* FactoryCode, char* LineCode, char* SpecCode, char* DeviceCode, char* ProductItemNo, char* SemiProductItemNo);
#using "C:\\Users\\zhi\\Desktop\\dll\\MES.dll"
using namespace System;
using namespace MES;
char* GetOrder(char* ServerUrl, char* FactoryCode, char* LineCode)
{
MESClient^ meh = gcnew MESClient();
String^ url = gcnew String(ServerUrl);
String^ code = gcnew String(FactoryCode);
String^ line = gcnew String(LineCode);
String^ resultstring = meh->GetOrder(url, code, line);
char* result = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToCoTaskMemAnsi(resultstring);
return result;
}
char* GetParam(char* ServerUrl, char* FactoryCode, char* LineCode, char* SpecCode, char* DeviceCode, char* ProductItemNo, char* SemiProductItemNo)
{
MESClient^ meh = gcnew MESClient();
String^ url = gcnew String(ServerUrl);
String^ code = gcnew String(FactoryCode);
String^ line = gcnew String(LineCode);
String^ speccode = gcnew String(SpecCode);
String^ device = gcnew String(DeviceCode);
String^ product = gcnew String(ProductItemNo);
String^ semproduct = gcnew String(SemiProductItemNo);
String^ resultstring = meh->GetParam(url, code, line, speccode, device, product, semproduct);
char* result = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToCoTaskMemAnsi(resultstring);
return result;
}