C++ – ESP Error when I call an API function

cfunctionimportwinapi

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

Best Answer

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).