gpt4 book ai didi

c++ - __stdcall 类型定义结构

转载 作者:行者123 更新时间:2023-11-30 05:04:15 26 4
gpt4 key购买 nike

我正在用 C++ 编写我的第一个 DLL。使用 __declspec(dll_export),我可以使用 C 包装器在 Python 和 C++ 上读取它。但我现在也想在 C 上阅读它,所以我现在必须添加 __stdcall 约定。但我不知道如何将它应用于 typedef struct。例如:

Projet.h

#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 接口(interface),因此您应该防止 C++ 异常跨越语言边界。

extern "C" 应该有条件地包含在内:

#ifdef __cplusplus
extern "C"
{
#endif

#ifdef __cplusplus
}
#endif

关于c++ - __stdcall 类型定义结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48985778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com