Помогите с dll.

Модераторы: Hawk, Romeo, Absurd, DeeJayC, WinMain

Ответить
thisPROgame
Сообщения: 1
Зарегистрирован: 21 май 2014, 16:03

Требуется загрузить функцию сортировки из dll. dll создана функция в main загружена. Но при компиляции просто все вылетает. Или я не правильно ее обозначаю или еще, что либо. Помогите.
main.c

Код: Выделить всё

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <windows.h>

//__declspec(dllexport) int heapsort(int a[], int n);
//__declspec(dllexport) void insertion (int mas[], int n) ;


int getrand(int min, int max)
{
 return (double)rand() / (RAND_MAX + 1.0) * (max - min) + min;
}

double wtime()
{
 struct timeval t;
 gettimeofday(&t, NULL);[url]http://vk.com/doc107821109_298789145?hash=3826f81925065797bc&dl=df4c72614fa02e51a4[/url]
 return (double)t.tv_sec + (double)t.tv_usec * 1E-6;
}

input(int *n){
    int k;
    printf("Enter the degree of N = ");
    scanf("%d",&k);
    /*if(k > '0' && k < '9'){
    }
    else{
        printf ("Error: Incorrect input");
        exit(1);
    }*/
    *n = pow(*n,k);
}

int main () {
    int i, k, *mas, n=2, sort, a;
    double t;
    HINSTANCE h;
    void (*heapsort) (int *str);
    void (*insertion) (int *str);
    h = LoadLibrary("sort.dll");
     if (!h)
  {
    printf("error reding dll\n");
    return;
  }
    heapsort = (int (*) (int *str, int))
        GetProcAddress(h,"heapsort");
        if (!heapsort)
  {
    printf("Error! In library dll. dont have function heapsort\n");
    return;
  }
    insertion = (void (*) (int *str, int))
        GetProcAddress(h,"insertion");
        if (!insertion)
  {
    printf("Error! In library dll. dont have function insertion\n");
    return;
  }
    input(&n);
    mas = (int *)malloc(sizeof(int)*n);
    for (i = 0; i < n; i++){
        mas[i] = getrand (1, 10000);
    }
    printf("%d\n", n);
    printf ("heap or insertion? (type 1 or 0)\n");
    scanf ("%d", sort);
    if (sort > 1 || sort < 0){
            printf("ERROR : incorrect input");
            exit(1);
    }

    t = wtime();
    //if (sort == 1) {
        *heapsort;
    //}
    //else{
        //insertion("test");
    //}
    t = wtime() - t;
    printf("Elapsed time: %.6f sec.\n", t);
    FreeLibrary(h);
    return 0;
}
sort.cpp

Код: Выделить всё

#include "main.h"
#include <stdio.h>
#include <stdlib.h>

extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            // attach to process
            // return FALSE to fail DLL load
            break;

        case DLL_PROCESS_DETACH:
            // detach from process
            break;

        case DLL_THREAD_ATTACH:
            // attach to thread
            break;

        case DLL_THREAD_DETACH:
            // detach from thread
            break;
    }
    return TRUE; // succesful
}

int DLL_EXPORT heapsort(int a[], int n)
{
  int sh = 0, b = 0, i;
  for (i = 0; i < n; ++i)
  while (1)
  {
    b = 0;
    for (i = 0; i < n; ++i)
    {
      if (i*2 + 2 + sh < n)
      {
        if (a[i+sh] > a[i*2 + 1 + sh] || a[i + sh] > a[i*2 + 2 + sh])
	{
	  if (a[i*2+1+sh] < a[i*2+2+sh])
	  {
	    swap (&a[i+sh], &a[i*2+1+sh]);
	    b = 1;
	  }
	  else if (a[i*2+2+sh] < a[i*2+1+sh])
	  {
	    swap (&a[i+sh],&a[i*2+2+sh]);
	    b = 1;
	  }
	}
      }
      else if (i * 2 + 1 + sh < n)
      {
        if (a[i+sh] > a[i*2+1+sh])
	{
	  swap (&a[i+sh], &a[i*2+1+sh]);
	  b=1;
	}
      }
    }
    if (!b) sh++;
    if (sh+2==n)
      break;
  }
  return 0;
}

void swap (int *a, int *b)
{

  int t = *a;
  *a = *b;
  *b = t;
}

void DLL_EXPORT insertion (int mas[], int n) {
int i, j, temp;
for (i = 1; i < n; i++)
{
    temp = mas[i];
    for (j = i - 1; j >= 0; j--)
    {
        if (mas[j] < temp)
            break;

        mas[j + 1] = mas[j];
        mas[j] = temp;
    }
}
sort.h

Код: Выделить всё

#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C"
{
#endif

int DLL_EXPORT heapsort(int a[], int n);
void swap (int *a, int *b);
void DLL_EXPORT insertion (int mas[], int n);

#ifdef __cplusplus
}
#endif

#endif
Аватара пользователя
Romeo
Сообщения: 3126
Зарегистрирован: 02 мар 2004, 17:25
Откуда: Крым, Севастополь
Контактная информация:

Что значит при комипиляции вылетает? При компиляции или при запуске?

Если всё-таки при запуске и проблема в том, что GetProcAddress возвращает NULL (это лекго проверить в дебаге), то как вариант можно проверить, что в прокте dll в настройках определён директива препроцессора BUILD_DLL.
Entites should not be multiplied beyond necessity @ William Occam
---
Для выделения С++ кода используйте конструкцию [ code=cpp ] Код [ /code ] (без пробелов)
---
Сообщение "Спасибо" малоинформативно. Благодарность правильнее высказать, воспользовавшись кнопкой "Reputation" в виде звёздочки, расположенной в левом нижнем углу рамки сообщения.
Ответить