Jump to content

Cara membuat DLL sendiri

From Haidhi Wiki
// mylib.cpp

#include <windows.h>
 
#define EOF (-1)
 
#ifdef __cplusplus   
extern "C" {        
#endif
 
__declspec(dllexport) int tambah(int a, int b) {
    return a + b;
}

__declspec(dllexport) int factorial(int a){
    int result = 1;
    for(int i = 1; i <=a; i++){
        result *= i;
    }
    return result;
}

#ifdef __cplusplus

}
#endif

compile

 
# Akan menghasilkan file mylib.dll
g++ -shared -o mylib.dll mylib.cpp


// main.cpp

#include <windows.h>
#include <iostream>

typedef int (*TambahFunc)(int, int);
typedef int(*FactorialFunc)(int);

int main() {
    HINSTANCE hDll = LoadLibrary("mylib.dll");
    if (!hDll) {
        std::cout << "Gagal load DLL" << std::endl;
        return 1;
    }

    TambahFunc tambah = (TambahFunc)GetProcAddress(hDll, "tambah");
    if (!tambah) {
        std::cout << "Gagal cari fungsi tambah" << std::endl;
        return 1;
    }
    int hasil = tambah(5, 7);
    std::cout << "Hasil: " << hasil << std::endl; 

    FactorialFunc factorial = (FactorialFunc)GetProcAddress(hDll, "factorial");
    if (!factorial){
        std::cout << "Gagal cari fungsi factorial" << std::endl;
        return 1;
    }
    int hasil2 = factorial(5);
    std::cout << "Hasil2: " << hasil2 << std::endl; 


    FreeLibrary(hDll);
    return 0;
}

compile & run

 
g++ main.cpp -o main.exe
main.exe