[programmare] C e DLL Clicca QUI per vedere il messaggio nel forum |
cato |
mi sto avventurando nel magico mondo delle DLL.
il mio scopo è madare un array di char da un programma C a una funzione di una DLL (in delphi)
code: #include <stdio.h>
#include <windows.h>
#include <string.h>
typedef int (CALLBACK* LPFNDLLFUNC1)(char*);
//CALLBACK* LPFNDLLFUNC1();
HINSTANCE hDLL; // Handle to DLL
LPFNDLLFUNC1 lpfnDllFunc1; // Function pointer
int
main (){
int a;
char stringa[32];
char *s;
hDLL = LoadLibrary("test.dll");
if (hDLL != NULL){
lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL,"hello");
if (!lpfnDllFunc1)
{
// handle the error
FreeLibrary(hDLL);
return 1;
}
else
{
stringa[0]='a';
stringa[1]='b';
stringa[2]='a';
stringa[3]='c';
stringa[4]='o';
a=lpfnDllFunc1(stringa);
printf("->%d",a);
}
}
}
qui la dll
code: library test;
{prima prova di DLL}
uses
SysUtils,
Classes,
finestra in 'finestra.pas' {Form1},
Unit2 in 'Unit2.pas' {Form2};
function hello(stringa:array of pchar):integer;
begin
result:=100;
writeln(stringa[1]);
end;
exports
hello;
{$R *.RES}
var
Form1: TForm1;
begin
writeln('prova');
//form1 := Tform1.Create(Nil);
//form1.ShowModal;
//form1.Free;
end.
chiaramente non funziona.... :roll: |
yeah |
1) Sei obbligato ad usare Dephi per la DLL?
2) Che problemi ti da?
3) Con che cosa compili e con che parametri? |
cato |
1)per il lato delphi no...
2)errori di memoria
3)gcc |
yeah |
1) proviamo prima a risolvere gli altri 2 problemi :)
2) errori di esecuzione o di compilazione? Puoi postare il testo?
3) e con che parametri?
[edit]
Nel frattempo ci ho provato anche io :) ma tutto in C
dll.c
code: #include <windows.h>
__declspec(dllexport) void printy(char *str)
{
MessageBox(NULL, str, "printy.dll", MB_OK);
}
Compilazione della dll:
gcc -c -Wall dll.c
dllwrap dll.o --dllname=printy.dll -Wall
programma di prova
p.c
code: #include <windows.h>
int main(int argc, char *argv[])
{
HINSTANCE dllHandle;
void (*my_func)(char *str);
dllHandle = LoadLibrary("printy.dll");
if(!dllHandle)
{
MessageBox(NULL, "Dll non caricata!", argv[0], MB_OK);
return 0;
}
my_func = (void *) GetProcAddress(dllHandle, "printy");
if(my_func)
my_func("Ciao :)");
else
MessageBox(NULL, "Funzione non caricata!", argv[0], MB_OK);
FreeLibrary(dllHandle);
return 0;
}
|
yeah |
Ora che riguardo il tuo codice, ho notato un problema: code: stringa[0]='a';
stringa[1]='b';
stringa[2]='a';
stringa[3]='c';
stringa[4]='o';
Non termini la stringa con un '\0'. Se il problema di memoria è una violazione di segmento (del tipo "la memoria non poteva essere (read)" o simile) con buona probabilità è colpa di quello :)
Per semplicità puoi sostituirlo con un strcpy(stringa, "abaco");
:) |
cato |
risolto: mancava un "cdecl" :P
code:
function hello(var stringa:array of integer):integer; cdecl;
begin
writeln('DLL:');
writeln(stringa[0]);
writeln(stringa[1]);
writeln(stringa[2]);
writeln(stringa[3]);
writeln(stringa[4]);
result:=100;
end;
|
|
|
|