Search code examples
c#.netpinvokedllimport

DllImport not executing functions in library but no error codes


I am developing on Windows 11 and have been given an unmanaged C dll. However I am running into the issue that I am unable to execute the functions in the library. I do not get any errors, the function calls just don't execute.

The C library function code signature is:

int connectToDeviceBySerial(const char * const serialNumber, uintptr_t* deviceContextPtr)

I am using DllImport like so:

internal const string laserTackDllPath = @"External Dependencies\spectrlib_core_shared.dll";

[DllImport(laserTackDllPath, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
static private extern int connectToDeviceBySerial(string serial, ref ulong deviceHandle);

and I am calling it in my code like this:

private void ConnectToDeviceInternal()
{
    int response = connectToDeviceBySerial(SerialNumber, ref DeviceHandle);
    if (response != OK) { throw new OESException(response); };
}

which is working perfectly fine on Windows 11. However, when I am using the same code on Windows 10, the function connectToDeviceBySerial never returns. I don't get an error, it's just that nothing happens and the program flow does not continue. As this code is part of an application with UI, this is executed in the background and the application does not freeze.

To check what happens, I added the following function to the C library (in the code file):

int justATest() {
    FILE* fp;
    fp = fopen("c_log.txt", "a");
    fprintf(fp, "58\n");
    fclose(fp);

    return OK;
}

and the corresponding header file:

#define LIBSHARED_AND_STATIC_EXPORT __declspec(dllexport)
#ifndef AS_CORE_LIBRARY
LIBSHARED_AND_STATIC_EXPORT
#endif
int justATest();

and also called it from my C# code:

[DllImport(laserTackDllPath, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static private extern int justATest();
int l = justATest();

Again, this works in Windows 11, but not Windows 10. It seems like the function call is never executed in the actual C library.

Is there anything I need to change for Windows 10? Does DllImport work differently on Windows 10?


Solution

  • I found the issue. The code is correct and works on both Windows 11 and Windows 10. The issue was that I needed to install the Visual C++ Redistributable on Windows 10. As there was no error without the redistributable, it took me some time to figure this out. I'm presenting this answer so everyone with a similar problem can check whether they've got the Redistributable installed.