对 PInvoke 函数“Test!DllCall::initDll”的调用堆栈不平衡
这是一个不寻常的问题。
我发现只有在通过 Visual Studio 运行程序时才会引发该错误。如果我编译该应用程序并运行编译后的程序,它就可以正常工作。有什么想法会导致这种情况吗?
我有一个 C# 类,它通过 JNI 调用 Java DLL(通过 excelsior jet 编译)中的方法。
当我编译并运行 C# 类和可执行文件时,一切正常。现在我已将 C# 类构建为 DLL,并尝试从另一个类调用它。
此时我收到以下错误消息: 对 PInvoke 函数“Test!DllCall::initDll”的调用使堆栈不平衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配。
谁能解释一下为什么我会遇到这个问题以及如何解决它?
如果您需要更多代码/信息,请告诉我
这是 C# 代码:
using System;
using System.Runtime.InteropServices;
using System.Text;
public class DllCall
{
[DllImport("Stubs")]
public static extern int initDll(String userDllName);
[DllImport("Stubs")]
public static extern void finalizeDll();
[DllImport("Stubs")]
public static extern UInt32 newClassInstance();
[DllImport("Stubs")]
public static extern int invokeStaticMethod();
[DllImport("Stubs")]
public static extern String request(UInt32 hClassInst, String input);
[DllImport("Stubs")]
public static extern void close();
[DllImport("Stubs")]
public static extern void voidtest(UInt32 hClassInst);
}
public class Test
{
public UInt32 hClass;
public Test()
{
//when compiled as a DLL this line throws the error.
int rc = DllCall.initDll("dllClass.dll");
Console.Write("---> initDll() rc = {0}\n", rc);
hClass = DllCall.newClassInstance();
Console.Write("---> hClass = {0}\n", hClass);
}
// When compiled as an executable this method runs fine.
public static void Main(string[] args)
{
int rc = DllCall.initDll("dllClass.dll");
string rs;
Console.Write("---> initDll() rc = {0}\n", rc);
UInt32 hClass = DllCall.newClassInstance();
Console.Write("---> hClass = {0}\n", hClass);
rs = DllCall.request(hClass, "moo");
Console.Write("---> request() rs = {0}\n", rs);
DllCall.close();
DllCall.finalizeDll();
}
public string request( string xmlInput )
{
string rs;
rs = DllCall.request(hClass, xmlInput);
Console.Write("---> request() rs = {0}\n", rs);
return rs;
}
public void finalizeDll()
{
DllCall.finalizeDll();
}
public void closeConnection()
{
DllCall.close();
}
}
我知道这是很多代码,但根据要求,这里是 C Dll 中的代码......
#include <jni.h>
#include <windows.h>
JNIEnv *env;
JavaVM *jvm;
HANDLE hUserDll;
jclass jClass;
char* dllname;
/*
* Load dll.
*/
HANDLE loadDll(char* name)
{
HANDLE hDll = LoadLibrary (name);
if (!hDll) {
printf ("Unable to load %s\n", name);
exit(1);
}
printf ("%s loaded\n", name);
return hDll;
}
jint (JNICALL * JNI_GetDefaultJavaVMInitArgs_func) (void *args);
jint (JNICALL * JNI_CreateJavaVM_func) (JavaVM **pvm, void **penv, void *args);
/*
* Initialize JET run-time.
*/
void initJavaRT(HANDLE myDllHandle, JavaVM** pjvm, JNIEnv** penv)
{
int result;
JavaVMInitArgs args;
JNI_GetDefaultJavaVMInitArgs_func =
(jint (JNICALL *) (void *args))
GetProcAddress (myDllHandle, "JNI_GetDefaultJavaVMInitArgs");
JNI_CreateJavaVM_func =
(jint (JNICALL *) (JavaVM **pvm, void **penv, void *args))
GetProcAddress (myDllHandle, "JNI_CreateJavaVM");
if(!JNI_GetDefaultJavaVMInitArgs_func) {
printf ("%s doesn't contain public JNI_GetDefaultJavaVMInitArgs\n", dllname);
exit (1);
}
if(!JNI_CreateJavaVM_func) {
printf ("%s doesn't contain public JNI_CreateJavaVM\n", dllname);
exit (1);
}
memset (&args, 0, sizeof(args));
args.version = JNI_VERSION_1_2;
result = JNI_GetDefaultJavaVMInitArgs_func(&args);
if (result != JNI_OK) {
printf ("JNI_GetDefaultJavaVMInitArgs() failed with result %d\n", result);
exit(1);
}
/*
* NOTE: no JVM is actually created
* this call to JNI_CreateJavaVM is intended for JET RT initialization
*/
result = JNI_CreateJavaVM_func (pjvm, (void **)penv, &args);
if (result != JNI_OK) {
printf ("JNI_CreateJavaVM() failed with result %d\n", result);
exit(1);
}
printf ("JET RT initialized\n");
fflush (stdout);
}
/*
* Look for class.
*/
jclass lookForClass (JNIEnv* env, char* name)
{
jclass clazz = (*env)->FindClass (env, name);
if (!clazz) {
printf("Unable to find class %s\n", name);
exit(1);
}
printf ("Class %s found\n", name);
fflush (stdout);
return clazz;
}
int initDll(char* userDllName)
{
jClass = NULL;
hUserDll = loadDll(userDllName);
dllname = userDllName;
initJavaRT(hUserDll, &jvm, &env);
jClass = lookForClass(env, "mooMain/mooGeminiX3/mooGeminiX3IFX");
return jClass ? 1 : 0;
}
/** finalizeDll() - stop Java VM
*/
void finalizeDll ()
{
(*jvm)->DestroyJavaVM (jvm);
FreeLibrary((HMODULE)hUserDll);
hUserDll = NULL;
jClass = NULL;
}
jobject newClassInstance()
{
jmethodID MID_init;
jobject obj;
jstring name;
jobjectArray ret;
jclass sclass;
jobjectArray arr;
MID_init = (*env)->GetMethodID (env, jClass, "<init>", "([Ljava/lang/String;)V");
if (!MID_init) {
printf("Error: dllClass.<init>() not found\n");
return NULL;
}
sclass = (*env)->FindClass(env, "java/lang/String");
arr = (*env)->NewObjectArray(env, 6, sclass, NULL);
name = (*env)->NewStringUTF(env,"@C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\mooRoot.cfg");
(*env)->SetObjectArrayElement(env,arr,0,name);
name = (*env)->NewStringUTF(env,"-cfg");
(*env)->SetObjectArrayElement(env,arr,1,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-CVS\\moo-PCB\\Application\\Configuration\\Linear\\Application\\moo.cfg");
(*env)->SetObjectArrayElement(env,arr,2,name);
name = (*env)->NewStringUTF(env,"-startupLog");
(*env)->SetObjectArrayElement(env,arr,3,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\Log\\mooStartup.log");
(*env)->SetObjectArrayElement(env,arr,4,name);
name = (*env)->NewStringUTF(env,"-geminiX3");
(*env)->SetObjectArrayElement(env,arr,5,name);
obj = (*env)->NewObject(env, jClass, MID_init, arr);
if (!obj) {
printf("Error: failed to allocate an object\n");
return NULL;
}
return obj;
}
const char* request(jobject obj, char* input )
{
jstring inputString;
jstring outputString;
const char *nativeString;
jmethodID mID = (*env)->GetMethodID (env, jClass, "request", "(Ljava/lang/String;)Ljava/lang/String;");
if (!mID){
printf("\nError: dllClass.request() not found\n");
return 0;
}
printf("here"); fflush(stdout);
inputString = (*env)->NewStringUTF(env, input);
printf("here2"); fflush(stdout);
outputString = (*env)->CallObjectMethod(env, obj, mID, inputString);
nativeString = (*env)->GetStringUTFChars(env, outputString, 0);
return nativeString;
}
void voidtest(jobject obj )
{/*
jmethodID mID = (*env)->GetMethodID (env, jClass, "request", "([Ljava/lang/String;)[Ljava/lang/String;");
if (!mID){
printf("\nError: dllClass.request() not found\n");
return 0;
}
char inputString[] = (*env)->NewStringUTF(env, "Moo");
(*env)->CallVoidMethod(env, obj, mID, inputString);*/
}
void close()
{
jmethodID mID = (*env)->GetMethodID (env, jClass, "close", "()V");
if (!mID){
printf("\nError: dllClass.close() not found\n");
}
(*env)->CallVoidMethod(env,jClass, mID);
}
int invokeStaticMethod()
{
jmethodID MID_init;
jobject obj;
jstring name;
jobjectArray ret;
jclass sclass;
jobjectArray arr;
jmethodID mID = (*env)->GetStaticMethodID(env, jClass, "start", "([Ljava/lang/String;)V");
if (!mID){
printf("\nError: dllClass.sfstart() not found\n");
return 0;
}
sclass = (*env)->FindClass(env, "java/lang/String");
arr = (*env)->NewObjectArray(env, 5, sclass, NULL);
name = (*env)->NewStringUTF(env,"@C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\mooRoot.cfg");
(*env)->SetObjectArrayElement(env,arr,0,name);
name = (*env)->NewStringUTF(env,"-cfg");
(*env)->SetObjectArrayElement(env,arr,1,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-CVS\\moo-PCB\\Application\\Configuration\\Linear\\Application\\moo.cfg");
(*env)->SetObjectArrayElement(env,arr,2,name);
name = (*env)->NewStringUTF(env,"-startupLog");
(*env)->SetObjectArrayElement(env,arr,3,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\Log\\mooStartup.log");
(*env)->SetObjectArrayElement(env,arr,4,name);
(*env)->CallStaticVoidMethod(env,jClass, mID, arr);
printf("\nGot to here\n");
return 1;
}
亲切的问候
Ash
Bit of an unusual question.
I have worked out that the error is only thrown when running the program via visual studio. If I compile the application and run the compiled program it works fine. Any ideas what would cause this?
I have a C# class that calls a method in a Java DLL ( compiled through excelsior jet ) via JNI.
When I compile and run the C# class an an executable everything works fine. Now I have built the C# class as a DLL and am trying to call it from another class.
At this point I get the followign error message:
A call to PInvoke function 'Test!DllCall::initDll' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
Could anyone explain why Im getting this and how to fix it?
Please let me know if you need anymore code/information
Heres the C# code:
using System;
using System.Runtime.InteropServices;
using System.Text;
public class DllCall
{
[DllImport("Stubs")]
public static extern int initDll(String userDllName);
[DllImport("Stubs")]
public static extern void finalizeDll();
[DllImport("Stubs")]
public static extern UInt32 newClassInstance();
[DllImport("Stubs")]
public static extern int invokeStaticMethod();
[DllImport("Stubs")]
public static extern String request(UInt32 hClassInst, String input);
[DllImport("Stubs")]
public static extern void close();
[DllImport("Stubs")]
public static extern void voidtest(UInt32 hClassInst);
}
public class Test
{
public UInt32 hClass;
public Test()
{
//when compiled as a DLL this line throws the error.
int rc = DllCall.initDll("dllClass.dll");
Console.Write("---> initDll() rc = {0}\n", rc);
hClass = DllCall.newClassInstance();
Console.Write("---> hClass = {0}\n", hClass);
}
// When compiled as an executable this method runs fine.
public static void Main(string[] args)
{
int rc = DllCall.initDll("dllClass.dll");
string rs;
Console.Write("---> initDll() rc = {0}\n", rc);
UInt32 hClass = DllCall.newClassInstance();
Console.Write("---> hClass = {0}\n", hClass);
rs = DllCall.request(hClass, "moo");
Console.Write("---> request() rs = {0}\n", rs);
DllCall.close();
DllCall.finalizeDll();
}
public string request( string xmlInput )
{
string rs;
rs = DllCall.request(hClass, xmlInput);
Console.Write("---> request() rs = {0}\n", rs);
return rs;
}
public void finalizeDll()
{
DllCall.finalizeDll();
}
public void closeConnection()
{
DllCall.close();
}
}
I know this is a lot of code but as requested heres the code in the C Dll.....
#include <jni.h>
#include <windows.h>
JNIEnv *env;
JavaVM *jvm;
HANDLE hUserDll;
jclass jClass;
char* dllname;
/*
* Load dll.
*/
HANDLE loadDll(char* name)
{
HANDLE hDll = LoadLibrary (name);
if (!hDll) {
printf ("Unable to load %s\n", name);
exit(1);
}
printf ("%s loaded\n", name);
return hDll;
}
jint (JNICALL * JNI_GetDefaultJavaVMInitArgs_func) (void *args);
jint (JNICALL * JNI_CreateJavaVM_func) (JavaVM **pvm, void **penv, void *args);
/*
* Initialize JET run-time.
*/
void initJavaRT(HANDLE myDllHandle, JavaVM** pjvm, JNIEnv** penv)
{
int result;
JavaVMInitArgs args;
JNI_GetDefaultJavaVMInitArgs_func =
(jint (JNICALL *) (void *args))
GetProcAddress (myDllHandle, "JNI_GetDefaultJavaVMInitArgs");
JNI_CreateJavaVM_func =
(jint (JNICALL *) (JavaVM **pvm, void **penv, void *args))
GetProcAddress (myDllHandle, "JNI_CreateJavaVM");
if(!JNI_GetDefaultJavaVMInitArgs_func) {
printf ("%s doesn't contain public JNI_GetDefaultJavaVMInitArgs\n", dllname);
exit (1);
}
if(!JNI_CreateJavaVM_func) {
printf ("%s doesn't contain public JNI_CreateJavaVM\n", dllname);
exit (1);
}
memset (&args, 0, sizeof(args));
args.version = JNI_VERSION_1_2;
result = JNI_GetDefaultJavaVMInitArgs_func(&args);
if (result != JNI_OK) {
printf ("JNI_GetDefaultJavaVMInitArgs() failed with result %d\n", result);
exit(1);
}
/*
* NOTE: no JVM is actually created
* this call to JNI_CreateJavaVM is intended for JET RT initialization
*/
result = JNI_CreateJavaVM_func (pjvm, (void **)penv, &args);
if (result != JNI_OK) {
printf ("JNI_CreateJavaVM() failed with result %d\n", result);
exit(1);
}
printf ("JET RT initialized\n");
fflush (stdout);
}
/*
* Look for class.
*/
jclass lookForClass (JNIEnv* env, char* name)
{
jclass clazz = (*env)->FindClass (env, name);
if (!clazz) {
printf("Unable to find class %s\n", name);
exit(1);
}
printf ("Class %s found\n", name);
fflush (stdout);
return clazz;
}
int initDll(char* userDllName)
{
jClass = NULL;
hUserDll = loadDll(userDllName);
dllname = userDllName;
initJavaRT(hUserDll, &jvm, &env);
jClass = lookForClass(env, "mooMain/mooGeminiX3/mooGeminiX3IFX");
return jClass ? 1 : 0;
}
/** finalizeDll() - stop Java VM
*/
void finalizeDll ()
{
(*jvm)->DestroyJavaVM (jvm);
FreeLibrary((HMODULE)hUserDll);
hUserDll = NULL;
jClass = NULL;
}
jobject newClassInstance()
{
jmethodID MID_init;
jobject obj;
jstring name;
jobjectArray ret;
jclass sclass;
jobjectArray arr;
MID_init = (*env)->GetMethodID (env, jClass, "<init>", "([Ljava/lang/String;)V");
if (!MID_init) {
printf("Error: dllClass.<init>() not found\n");
return NULL;
}
sclass = (*env)->FindClass(env, "java/lang/String");
arr = (*env)->NewObjectArray(env, 6, sclass, NULL);
name = (*env)->NewStringUTF(env,"@C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\mooRoot.cfg");
(*env)->SetObjectArrayElement(env,arr,0,name);
name = (*env)->NewStringUTF(env,"-cfg");
(*env)->SetObjectArrayElement(env,arr,1,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-CVS\\moo-PCB\\Application\\Configuration\\Linear\\Application\\moo.cfg");
(*env)->SetObjectArrayElement(env,arr,2,name);
name = (*env)->NewStringUTF(env,"-startupLog");
(*env)->SetObjectArrayElement(env,arr,3,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\Log\\mooStartup.log");
(*env)->SetObjectArrayElement(env,arr,4,name);
name = (*env)->NewStringUTF(env,"-geminiX3");
(*env)->SetObjectArrayElement(env,arr,5,name);
obj = (*env)->NewObject(env, jClass, MID_init, arr);
if (!obj) {
printf("Error: failed to allocate an object\n");
return NULL;
}
return obj;
}
const char* request(jobject obj, char* input )
{
jstring inputString;
jstring outputString;
const char *nativeString;
jmethodID mID = (*env)->GetMethodID (env, jClass, "request", "(Ljava/lang/String;)Ljava/lang/String;");
if (!mID){
printf("\nError: dllClass.request() not found\n");
return 0;
}
printf("here"); fflush(stdout);
inputString = (*env)->NewStringUTF(env, input);
printf("here2"); fflush(stdout);
outputString = (*env)->CallObjectMethod(env, obj, mID, inputString);
nativeString = (*env)->GetStringUTFChars(env, outputString, 0);
return nativeString;
}
void voidtest(jobject obj )
{/*
jmethodID mID = (*env)->GetMethodID (env, jClass, "request", "([Ljava/lang/String;)[Ljava/lang/String;");
if (!mID){
printf("\nError: dllClass.request() not found\n");
return 0;
}
char inputString[] = (*env)->NewStringUTF(env, "Moo");
(*env)->CallVoidMethod(env, obj, mID, inputString);*/
}
void close()
{
jmethodID mID = (*env)->GetMethodID (env, jClass, "close", "()V");
if (!mID){
printf("\nError: dllClass.close() not found\n");
}
(*env)->CallVoidMethod(env,jClass, mID);
}
int invokeStaticMethod()
{
jmethodID MID_init;
jobject obj;
jstring name;
jobjectArray ret;
jclass sclass;
jobjectArray arr;
jmethodID mID = (*env)->GetStaticMethodID(env, jClass, "start", "([Ljava/lang/String;)V");
if (!mID){
printf("\nError: dllClass.sfstart() not found\n");
return 0;
}
sclass = (*env)->FindClass(env, "java/lang/String");
arr = (*env)->NewObjectArray(env, 5, sclass, NULL);
name = (*env)->NewStringUTF(env,"@C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\mooRoot.cfg");
(*env)->SetObjectArrayElement(env,arr,0,name);
name = (*env)->NewStringUTF(env,"-cfg");
(*env)->SetObjectArrayElement(env,arr,1,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-CVS\\moo-PCB\\Application\\Configuration\\Linear\\Application\\moo.cfg");
(*env)->SetObjectArrayElement(env,arr,2,name);
name = (*env)->NewStringUTF(env,"-startupLog");
(*env)->SetObjectArrayElement(env,arr,3,name);
name = (*env)->NewStringUTF(env,"C:\\Users\\Ash\\Desktop\\moo-Test\\moo-Test\\Log\\mooStartup.log");
(*env)->SetObjectArrayElement(env,arr,4,name);
(*env)->CallStaticVoidMethod(env,jClass, mID, arr);
printf("\nGot to here\n");
return 1;
}
Kind Regards
Ash
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您的参数列表不正确或调用约定不匹配时,通常会发生这种情况。
您确实应该知道另一个 DLL 的调用约定是什么。如果是
cdecl
那么您将 P/invoke 更改为:您需要对所有导入执行此操作。
另一件要检查的事情是您的参数列表是否匹配。您只显示了边界的一侧,因此我们无法为您检查。如果你添加了另一面,那么我们也许能够发现一些东西。
添加 C 代码后进行了更新
我对您的代码有以下评论:
initDll
的 C# 声明的参数与 C 声明匹配,因此我非常有信心该问题是您的 C 代码使用cdecl
调用约定。 C# P/invoke 默认为stdcall
。更改其中之一的调用约定,但不能同时更改两者!您正在将
jobobject
与UInt32
进行匹配。我不确定这一点,因为我不知道 JNI。但是,我怀疑您应该返回jobject*
并与IntPtr
匹配。在我看来,jobject
似乎是一种类类型,而不是可以编组到 C# 的类型。最后,您的方法之一返回一个
字符串
。那是行不通的。 C# 编组器将尝试通过调用 CoTaskMemFree 来取消分配它。这可能会泄漏或爆炸,具体取决于您使用的 Windows 版本。您应该返回一个IntPtr
并使用Marshal.PtrToStringAnsi
将其编组为 C# 字符串。然后您需要释放 JNI 代码返回的内存。不确定你打算如何做到这一点。当然,如果您的字符串确实是 UTF-8,那么您需要复制到字节数组,然后使用 Encoding.UTF8 转换为 C# 字符串。This usually happens when you have an incorrect parameter list or mismatching calling convention.
You really ought to know what calling convention the other DLL is. If it is
cdecl
then you change your P/invoke to:You need to do this for all imports.
The other thing to check is that your parameter lists match. You only showed one side of the boundary so we can't check that for you. If you added the other side then we may be able to spot something.
Updated following addition of C code
I have the following comments on your code:
The parameters for the C# declaration of
initDll
match the C declaration so I'm pretty confident that the issue is that your C code usescdecl
calling convention. The C# P/invoke defaults tostdcall
. Change the calling convention in one or the other, but not both!You are matching
jobject
withUInt32
. I'm not sure about this since I don't know JNI. However, I suspect you should be returningjobject*
and matching withIntPtr
. It looks to me as thoughjobject
is a class type and not something that you can marshal to C#.Finally, one of your methods returns a
string
. That just won't work. The C# marshaller will attempt to deallocate it with a call toCoTaskMemFree
. That will leak or bomb, dependent on which Windows version you have. You should return anIntPtr
and useMarshal.PtrToStringAnsi
to marshal it into a C# string. Then you need to deallocate the memory returned by the JNI code. Not sure how you plan to do that. Of course, if your strings are really UTF-8 then you would need to copy to a byte array and then use Encoding.UTF8 to convert to a C# string.