开发者

Create a valid shared library in C

I'm doing some test to learn how to create shared library. The template for shared libraries in Code::Blocks is this

library.c

// The functions contained in this file are pretty dummy
// and are included only as a placeholder. Nevertheless,
// they *will* get included in the shared library if you
// don't remove them :)
//
// Obviously, you 'll have to write yourself the super-duper
// functions to include in the resulting library...
// Also, it's not necessary to write every function in this file.
// Feel free to add more files in this project. They will be
// included in the resulting library.

// A function adding two integers and returning the result
int SampleAddInt(int i1, int i2)
{
    return i1 + i2;
}

// A function doing nothing ;)
void SampleFunction1()
{
    // insert code here
}

// A function always returning zero
int SampleFunction2()
{
    // insert code here

    return 0;
}

I tried to compile it, and it compiled without any error or warning. But when i 开发者_开发技巧tried to use it with the ctyped.cdll.LoadLibrary("library path.dll") in python 3(that actually should work like the C function), it said that it wasn't a valid win32 application. Both python and code::blocks are 32 bit (code:blocks compile with gcc, and i tryed to use an installed version of mingw on my system, but it gives some error about a missing library) while i'm working on win 7 64bit

Do you know what the problem can be, or if i'm doing something wrong?

EDIT1: i'm on windows 7 64bit, in the specs file of the compiler is wrote: "Thread model: win32, gcc version 3.4.5 (mingw-vista special r3)" and i used as command

gcc.exe -shared -o library.dll library.c

in python i used

from ctypes import *

lib = cdll.LoadLibrary("C:\\Users\\Francesco\\Desktop\\C programmi\\Python\\Ctypes DLL\\library.dll")

and the error was

WindowsError: [Error 193] %1 is not a valid Win32 application

i installed both python3.1 and mingw from the binary package and not compiling them on my system

EDIT2: After reading Marc answer.

main.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

DLL_EXPORT int MySimpleSum(int A, int B);

#ifdef __cplusplus
}
#endif

#endif // __MAIN_H__

main.c

#include "main.h"

// a sample exported function
DLL_EXPORT int MySimpleSum(int A, int B)
{
    return A+B;
}

compiling options

gcc -c _DBUILD_DLL main.c
gcc -shared -o library.dll main.o -Wl,--out-implib,liblibrary.a

with gcc 4.5.2 still get the same error..


I believe in the windows environment you need to use the __declspec annotation. How to create a shared library and the use of __declspec is described here: DLL Creation in MingW.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜