Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am using SharpDX to render 3D graphics and i cannot get to work constant buffer in my shader since it contains an array. Currently it looks like this:

cbuffer cb0 : register(b0)
{
    matrix mWorld;
    matrix mView;
    matrix mProj;
    float4 vLightDir[2];
    float4 vLightColor[2];
    float4 vOutputColor;
}

But how to define a struct in C#, which will be correctly marshalled to such constant buffer in shader? In C# we don't have "excplicit" array initialization, e.g. this line of code i used in C++ will not work in C#:

struct cb0
{
  // ...
  Vector4 twos[2];// C#: Vector4[] twos;
// ...
}

I always set StructLayout option Pack=16 for my structs for alignment, but HOW to define such struct with C#? i have tried to define struct like this:

struct cb0_t//pack=16
        {
            public Matrix mWorld;
            public Matrix mView;
            public Matrix mProj;
            public Vector4 vLightDir0;
            public Vector4 vLightDir1;
            public Vector4 vLightColor0;
            public Vector4 vLightColor1;
            public Vector4 vOutputColor;
        }

Yes, it works with this, but this IS NOT COOL. Thank you, sorry for my english...

share|improve this question
    
unsafe+fixed is not solution here, as using 'manual' write to stream. it's all awful. –  Dmitrij A Mar 10 '14 at 9:01
    
Does Vector4[] twos = new Vector4[2] not work? That's strange, I guess. –  János Turánszki Mar 13 '14 at 11:38

1 Answer 1

It looks like you can use the MarshalAs attribute like so

[StructLayout(LayoutKind.Sequential, Pack = 16)]
public struct cb0_t
{
    public Matrix mWorld;
    public Matrix mView;
    public Matrix mProj;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
    public Vector4[] vLightDir;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
    public Vector4[] vLightColor;
    public Vector4 vOutputColor;
} 

You can take a look at this article, search for the heading Arrays.

Otherwise here's a shorter solution on StackOverflow.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.