ESP Error when I call an API function?

2019-08-28 07:47发布

问题:

platform : win32 , language : c++

I get this error when I call an imported function I declared:

Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.

And this is the code I used:

int LoadSongFromFile(int module);
typedef int (CALLBACK* loadSongT)(LPCTSTR);

//...

HINSTANCE dllHandle = NULL;
loadSongT loadSongPtr = NULL;

dllHandle = LoadLibrary(L"miniFMOD.dll");
loadSongPtr = (loadSongT)GetProcAddress(dllHandle,"SongLoadFromFile");

int songHandle = loadSongPtr(L"C:\b.xm");

The function I'm trying to call is SongLoadFromFile which requires one argument (in C# it is string so I assume its LPCTSTR in C++) and returns an int value.

Can somebody check what have I done wrong?

P.S. songHandle gets a weird negative value of -858993460

This is how I can call that function from C# :

[DllImport("MiniFMOD.dll")] public static extern int SongLoadFromFile(string name);

P.S. 2 : Using *typedef int (__cdecl loadSongT)(char);* doesn't return an error but songHandle comes up as 0.

miniFMOD.dll is an unmanaged library

回答1:

I think the other people are misunderstanding the question. It seems to me that minifmod.dll is a native library that exports a function named SongLoadFromFile. The existing code that calls this is managed code (C#) that uses DllImport to call the function in the native DLL. From what little information I could gather by a few Google searches, it looks as though it should be declared as follows:

typedef int (__cdecl * SongLoadFromFileT)(const char*);

Importantly, it is __cdecl calling convention and it takes an ANSI string instead of a Unicode string.

As an aside, I find it strange that I can't find ANYTHING on minifmod.dll other than a few forum posts on a Russian website and some SO questions from this guy. The only "legitimate" information I can find on minifmod is a small static library with similar functionality. I wonder if minifmod.dll is some kind of commercialized version of the static library; at least that would explain why there is not much public documentation about it.

Ah, I found it; it is a Delph port of minifmod (http://www.cobans.net/minifmod.php).



回答2:

You need to make sure to specify the right calling convention in your function pointer prototype ('CALLBACK' might be the wrong choice).



回答3:

The calling code uses the calling convention not matching that of the function being called. See this very similar question. You need to open the header defining that function (should come with the library you try to use), look the convention up and change your function pointer declaartion accordingly.