如何在C++/DirectX和HLSL之间共享一个结构体?

6

我正在学习C++和DirectX,发现在尝试保持HLSL着色器中的结构体与C++代码同步时出现了很多重复。由于两种语言具有相同的#include语义和头文件结构,因此我希望分享这些结构体。我已经成功地实现了这一点。

// ColorStructs.h
#pragma once

#ifdef __cplusplus

#include <DirectXMath.h>
using namespace DirectX;

using float4 = XMFLOAT4;

namespace ColorShader
{

#endif

    struct VertexInput
    {
        float4 Position;
        float4 Color;
    };

    struct PixelInput
    {
        float4 Position;
        float4 Color;
    };

#ifdef __cplusplus
}
#endif

问题在于编译这些着色器时,FXC告诉我我的像素着色器主函数上缺少语义的输入参数input parameter 'input' missing sematics

#include "ColorStructs.h"

void main(PixelInput input)
{
    // Contents elided
}

我知道我需要像 float4 Position : POSITION 这样的语义,但是我想不出一种不违反C++语法的实现方式。
是否有办法使结构在HLSL和C++之间通用?还是说这不可行,并且需要在两个源代码树之间复制结构体?

2
请注意,在不相关的头文件中放置“using namespace”通常被认为是一个坏主意(因为这会增加意外名称冲突的可能性)。 - user253751
1
这是个好观点!这最初是一个C++头文件,我忘记删除它了。感谢你指出来! - berwyn
1个回答

5
你可以使用函数宏在编译C++时去除语义规范符号。
#ifdef __cplusplus
#define SEMANTIC(sem) 
#else
#define SEMANTIC(sem) : sem
#endif

struct VertexInput
{
    float4 Position SEMANTIC(POSITION0);
    float4 Color SEMANTIC(COLOR0);
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接