在C#里创建和使用C风格数据结构
在C#里创建和使用C风格数据结构,即非托管的数据结构,可以提高性能。
1 数据结构的定义
看下面例子:
unsafe struct A {
public int x;
}
unsafe struct B {
public A a; //A内嵌到B中
public A* pa; //A链接到B中
public fixed int x[10]; //固定大小的数组内嵌到B中
public int* p; //大小未定的数组(首指针)链接到B中
}
所有数据结构,都用struct,不用class,而且struct每一个子元素都不能是class。
2 在非托管堆中创建对象或数组
看下面例子(静态类class C的源代码在后面给出):
A* pa=(A*)C.New(sizeof(A)); //相当于C里面的A* pa=(A*)malloc(sizeof(A));
B* pb=(B*)C.New(sizeof(B),5); //创建一个有5个元素的一维B数组
int** a1=(int**)C.New(sizeof(int), 2, 3); //创建一个2*3二维int数组,可用a1[i][j]访问每个元素
int** a2=(int**)C.New(new int[2,3]); //功能同上,并用0初始化数组
int** a3=(int**)C.New(new int[,]{{1, 2, 3},{4, 5, 6}}); //功能同上,并用指定值初始化数组
char* s=C.New("abcde"); //用字符串初始化char数组
C.Delete(pa, pb, a1, a2, a3, s); //释放上述对象的内存,参数个数任意
3 在栈中创建对象或数组
看下面例子:
A a; //建立栈对象a
B* pb=stackalloc B[5]; //创建一个有5个元素的一维栈数组
char* p1=stackalloc char[5];
C.Copy(p1, "Test"); //把字符串里的字符复制到栈数组里
C.Copy(p1, new[] { 'T', 'e', 's', 't', '\0' }); //把托管数组的数据复制到栈数组里
4 静态类class C的源代码
unsafe static class C {
[DllImport("msvcrt")]
public static extern void* malloc(uint size);
[DllImport("msvcrt")]
public static extern void* realloc(void* p, uint newsize);
[DllImpor
相关文档:
sd.xml文件:
<?xml version="1.0" encoding="gb2312"?>
<!--这是一个xml文件-->
<xml1>
<item name="1">第一个item</item>
<item name="2">
<item name="1">这个结点(1) ......
什么是空指针常量(null pointer constant)?
[6.3.2.3-3] An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.
这里告诉我们:0、0L、'\0'、3 - 3、0 * 17 (它们都是“integer constant expression”)以及 (void*)0 等都是空 ......
1:类似junit的断言,只是在assert中的断言,如果不满足的话就程序退出。
比如
#include <assert.h>
int main(void)
{
assert(6 < 5);
system("pause");
return 0;
}
在执行到assert(6 < 5);
的时候因为不满足断言,于是程序退出。
如果不想让assert(6 < 5)起作用,就在最上面添加宏定义# ......
C语言的回调函数思想代码:
#include <stdio.h>
void *max(void *base, unsigned int nmemb, unsigned int size,
int (*compar)(const void *, const void *))
{
int i;
void* max_data = base;
char* tmp = base;
&nbs ......