Nick
Nick

Reputation: 10499

Could not locate the function dllexport

I have my dll project

// .h
#pragma once

#include <stdio.h>

extern "C"
{
void __declspec(dllexport) __stdcall sort(int* vect, int size);
}

//.cpp
#include "stdafx.h"

void __declspec(dllexport) __stdcall sort(int* vect, int size)
{

}

And I have my console project:

#include <Windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>


/* Pointer to the sort function defined in the dll. */
typedef void (__stdcall *p_sort)(int*, int);


int _tmain(int argc, LPTSTR argv[])
{
    p_sort sort;

    HINSTANCE hGetProcIDDLL = LoadLibrary("dllproj.dll");

    if (!hGetProcIDDLL) 
    {
        printf("Could not load the dynamic library\n");
        return EXIT_FAILURE;
    }

    sort = (p_sort)GetProcAddress(hGetProcIDDLL, "sort");

    if (!sort)
    {
        FreeLibrary(hGetProcIDDLL);
        printf("Could not locate the function %d\n", GetLastError());
        return EXIT_FAILURE;
    }

    sort(NULL, 0);

    return 0;
}

The problem is that my function sort colud not be located, that is the function GetProcAddress always returns NULL.

Why? How can i fix it?

EDIT: using __cdecl (in the dll project instead of __stdcall) and Dependency Walker as suggested:

enter image description here

I also changed the following (in my main), but it still doesn't work.

typedef void (__cdecl *p_sort)(int*, int);

Upvotes: 2

Views: 254

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

The function is exported with a decorated name. For debugging purposes, when faced with such a situation, use dumpbin or Dependency Walker to find out what that name is. I predict it will be: _sort@8. The documentation for the __stdcall calling convention gives decoration rules as follows:

Name-decoration convention: An underscore (_) is prefixed to the name. The name is followed by the at sign (@) followed by the number of bytes (in decimal) in the argument list. Therefore, the function declared as int func( int a, double b ) is decorated as follows: _func@12

You'll have to do one of the following:

  1. Use the decorated name when importing.
  2. Use __cdecl to avoid the decoration.
  3. Export with a .def file to avoid the decoration.

Upvotes: 1

Related Questions