문제

I'm just learning neural networks and I would like to have the neuron's constructor receive a pointer to a section in an array that would be the chromosome. Something like this:

public int* ChromosomeSection;

public Neuron(int* chromosomeSection)
{
    ChromosomeSection = chromosomeSection;
}

So then I would create my neurons with something like this:

int[] Chromosome = new int[neuronsCount * neuronDataSize];

for (int n = 0; n < Chromosome.Length; n += neuronDataSize)
{
    AddNeuron(new Neuron(Chromosome + n));
}

Is it possible to do this in C#? I know C# supports some unsafe code. But I don't know how to tell the compiler that the line public Neuron(int* chromosomeSection) is unsafe.

Also, will I be able to do every operation that I would do in C++ or C? Is there any gotcha I should be aware of before starting to do it this way? Never worked with unsafe code in C# before.

도움이 되었습니까?

해결책

Eric Lippert has nice two-part series: References and Pointers, Part One and "managed pointers" implementation (References and Pointers, Part Two).

Here's a handy type I whipped up when I was translating some complex pointer-manipulation code from C to C#. It lets you make a safe "managed pointer" to the interior of an array. You get all the operations you can do on an unmanaged pointer: you can dereference it as an offset into an array, do addition and subtraction, compare two pointers for equality or inequality, and represent a null pointer. But unlike the corresponding unsafe code, this code doesn't mess up the garbage collector and will assert if you do something foolish, like try to compare two pointers that are interior to different arrays. (*) Enjoy!

Hope it helps.

다른 팁

Sounds like you could use ArraySegment<int> for what you are trying to do.

ArraySegment is a wrapper around an array that delimits a range of elements in that array. Multiple ArraySegment instances can refer to the same original array and can overlap.

The Array property returns the entire original array, not a copy of the array; therefore, changes made to the array returned by the Array property are made to the original array.

Yes this is perfectly possible in C#, although a pointer on alone is not sufficient information to use it in this way, you'd also need an Int32 length parameter, so you know how many times it's safe to increment that pointer without an overrun - this should be familiar if you're from a C++ background.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top