[英]__stdcall typedef struct
我正在用 C++ 編寫我的第一個 DLL。 使用__declspec(dll_export)
,我可以使用 C 包裝器在 Python 和 C++ 上讀取它。 但我現在也想在 C 上閱讀它,所以我現在必須添加__stdcall
約定。 但我不知道如何將它應用於typedef struct
。 例如:
項目文件
#pragma once
#include "Projet_inc.h"
class Projet // before, class _declspec(dll_export) Projet
{
public:
Projet();
~Projet();
int multiply(int arg1, int arg2);
int result;
};
projet_inc.h
#ifdef PROJET_EXPORTS
# define EXPORT __declspec(dllexport)
#else
# define EXPORT __declspec(dllimport)
#endif
#define CALLCONV_API __stdcall // before, this line didn't exist
extern "C" // C wrapper
{
typedef struct Projet Projet; // make the class opaque to the wrapper
Projet* EXPORT CALLCONV_API cCreateObject(void);
int EXPORT CALLCONV_API cMultiply(Projet* pDLLobject, int arg1, int arg2);
}
和Projet.cpp
#include "stdafx.h"
#include "Projet.h"
Projet::Projet() {}
Projet::~Projet() {}
int Projet::multiply(int arg1, int arg2) {
result = arg1 * arg2;
return result;
}
Projet* EXPORT CALLCONV_API cCreateObject(void)
{
return new Projet();
}
int EXPORT CALLCONV_API cMultiply(Projet* pDLLtest, int arg1, int arg2)
{
if (!pDLLtest)
return 0;
return pDLLtest->multiply(arg1, arg2);
}
在 Visual Studio 2017 上,編譯返回(第一行):
dir\projet_inc.h(11) : warning C4229: anachronisme utilisé : modificateurs de données ignorés
dir\projet_inc.h(13) :error C2059: erreur de syntaxe : '__declspec(dllimport)'
MSDN 告訴我,對於 C2059 錯誤,我必須先檢查 typedef 結構。
導出說明符僅適用於函數和變量。 調用約定說明符僅適用於函數。 所以類型別名(C 風格)應該是這樣的:
typedef struct Projet_I2M Projet_I2M;
出口規格應在報關前:
EXPORT Projet * CALLCONV_API cCreateObject(void);
您似乎有意導出 C 接口,因此您應該防止 C++ 異常跨越語言邊界。
應有條件地包含extern "C"
:
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef __cplusplus
}
#endif
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.