在 C# 中将指向数组部分的指针作为参数传递
我刚刚学习神经网络,我想让神经元的构造函数接收一个指向数组中作为染色体的部分的指针。像这样的东西:
public int* ChromosomeSection;
public Neuron(int* chromosomeSection)
{
ChromosomeSection = chromosomeSection;
}
那么我会用这样的东西创建我的神经元:
int[] Chromosome = new int[neuronsCount * neuronDataSize];
for (int n = 0; n < Chromosome.Length; n += neuronDataSize)
{
AddNeuron(new Neuron(Chromosome + n));
}
可以在 C# 中做到这一点吗?我知道 C# 支持一些不安全的代码。但我不知道如何告诉编译器该行 public Neuron(int*chromosomeSection)
是不安全的。
另外,我能够执行在 C++ 或 C 中执行的所有操作吗?在开始这样做之前我应该注意什么问题吗?以前从未使用过 C# 中的不安全代码。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Eric Lippert 有一个不错的两部分系列:参考和指针,第一部分 和“托管指针”实现(参考文献和指针,第二部分)。
希望有帮助。
Eric Lippert has nice two-part series: References and Pointers, Part One and "managed pointers" implementation (References and Pointers, Part Two).
Hope it helps.
听起来你可以使用
ArraySegment
对于你正在尝试做的事情。Sounds like you could use
ArraySegment<int>
for what you are trying to do.是的,这在 C# 中是完全可能的,尽管单独的指针不足以以这种方式使用它,但您还需要一个 Int32 长度参数,这样您就知道在不溢出的情况下可以安全地增加该指针多少次 -如果您有 C++ 背景,这应该很熟悉。
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.