Search code examples
c#.netpointersblockingcollection

C# Structs and pointers


I have the need to use a blocking collection, so that I can call a delegate asynchronously. Unfortunately the delegate has two parameters consisting of a struct and an additional string. The struct is used because it is the result from a call to an external c function via Interop.
Now I am looking at a way to avoid copying the struct when using the blocking collection.
Currently my code looks like this:

ConsumerQueue.Enqueue(new StructTransfer(structValue, stringValue));

The Consumer unpacks then the StructTransfer.

The StructTransfer currently looks like this

public struct Transfer{
    public StructValue structValue;
    public string stringValue;
    public Transfer(StructValue structValue, string stringValue){
      this.structValue=structValue;
      this.stringValue = stringValue;
    }
}

Is there an easy way with pointers to avoid the copy statements in the constructor, so that I can use the blocking collection easily?


Solution

  • The best way is to create the transfer class first.
    Use the struct as a field of the transfer class and use this field as a parameter when calling the interop. I guess there is no way to avoid the public field in this case.
    Thus memory usage should be minimized and one copy happens less.