Menu Home

C/C++

FileName Checker

/* A-Za-z0-9_- */ static int safe_filename(const char *f) { const char *start = f; for (; *f; f++) { if (!((unsigned)((*f | 32) – ‘a’) < 26 || (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) { if (f == start) return 0; else if […]

定制operator new记录分配的内存大小

调用operator new的时候在所分配的内存的第一个字节中记录本次new分配的内存大小。 void* operator new(size_t size) throw(bad_alloc){ if(size == 0) size = 1; void* address = NULL; size_t *p = NULL; while(true) { p = (size_t*)malloc(size + sizeof(size_t)); if(p) break; new_handler oldHandler = set_new_handler(0); set_new_handler(oldHandler); if(oldHandler) (*oldHandler)(); else throw bad_alloc(); } p[0] = size; address = (void*)(&p[1]); return address; } […]

C/C++调用JNI的区别

C++支持真正的对象而C不支持对象,所有C和C++调用JNI函数的时候会有一些细微的区别。 C++: JavaVM* vm JNIEnv* env = NULL; vm->GetEnv((void**)&env, JNI_VERSION_1_6); env->FindClass(“main”); C: JavaVM* vm JNIEnv* env = NULL; (*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6); (*env)->FindClass(env, “main”);

使用Invocation API调用Java类

InvocationApiTest.java import java.io.*; public class InvocationApiTest { public static void main(String[] args) { System.out.println(args[0]); } } invocationApi.c #include <jni.h> int main() { JNIEnv* env; JavaVM* vm; JavaVMInitArgs vm_args; JavaVMOption options[1]; jint res; jclass cls; jmethodID mid; jstring jstr; jclass stringClass; jobjectArray args; //1.生成Java虚拟机选项 options[0].optionString = “-Djava.class.path=.”; vm_args.version = JNI_VERSION_1_6; vm_args.options […]

c++: 获取delete[]中的数组大小

看一个小例子: #include <iostream> using namespace std; class A { public: A() { cout << “A::A()” << endl; } ~A() { cout << “A::~A()” << endl; } }; int main() { A* a = new A[5]; delete[] a; return 0; } 编译执行输出: A::A() A::A() A::A() A::A() A::A() A::~A() A::~A() A::~A() A::~A() […]

C: 数组形参

知识这个东西,真是知道的越多就不知道的越多,C/C++这塘水得多深啊,哈哈。 看下面3个片段: void fun(char a[100]) { fprintf(stderr, “%s\n”, a); } int main(void) { char aa[200] = “abcdef”; fun(aa); } void fun(char a[]) { fprintf(stderr, “%s\n”, a); } int main(void) { char aa[200] = “abcdef”; fun(aa); } void fun(char* a) { fprintf(stderr, “%s\n”, a); } int main(void) { char aa[200] = […]

Boost Serialization : Use Non-Default Constructors

#include <fstream> #include <cstring> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> class gps_position { public: gps_position(int size) { std::cout << “constructor: one” << std::endl; m_size = size; buf = (unsigned char *)malloc(size); memset(buf, 0, sizeof(buf)); } gps_position(int d, int m, float s, int bufSZ) : degrees(d), minutes(m), seconds(s) { std::cout << “constructor: two” […]