简体   繁体   English

__stdcall typedef 结构

[英]__stdcall typedef struct

I am writing my first DLL in C++.我正在用 C++ 编写我的第一个 DLL。 Using __declspec(dll_export) , I am able to read it on Python and C++ using a C wrapper.使用__declspec(dll_export) ,我可以使用 C 包装器在 Python 和 C++ 上读取它。 But I want now to read it on C too, so I have to add now the __stdcall convention.但我现在也想在 C 上阅读它,所以我现在必须添加__stdcall约定。 But I don't know how to apply it to a typedef struct .但我不知道如何将它应用于typedef struct For example:例如:

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 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);
}

and Projet.cppProjet.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);
}

On Visual Studio 2017, the compilation return (first lines) :在 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)'

And MSDN told that for C2059 error, I have to check on the typedef struct first. MSDN 告诉我,对于 C2059 错误,我必须先检查 typedef 结构。

Export specifiers apply only to functions and variables.导出说明符仅适用于函数和变量。 Calling convention specifiers apply only to functions.调用约定说明符仅适用于函数。 So type alias (C-style) should look like this:所以类型别名(C 风格)应该是这样的:

typedef struct Projet_I2M Projet_I2M;

Export specification should be infront of declaration:出口规格应在报关前:

EXPORT Projet * CALLCONV_API cCreateObject(void);

You seem to intentionally export C interface so you should prevent C++ exceptions from crossing language boundary.您似乎有意导出 C 接口,因此您应该防止 C++ 异常跨越语言边界。

extern "C" is should be conditionally included:应有条件地包含extern "C"

#ifdef __cplusplus
extern "C"
{
#endif

#ifdef __cplusplus
}
#endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM