Search Results

Search found 543 results on 22 pages for 'extern'.

Page 7/22 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Employing elegance in order to evade importing elephants: a case of excessive dll Imports

    - by user994179
    I am writing C# code that interfaces to a legacy (Feb 2012) C program, using DllImport. It works fine, but I need to call more than 30 different functions, turning my normally impeccable, exquisite code into something of near-elephantine proportions. Surely there must be a way around this? [Warning: those with weak stomachs may want to avert their eyes from what follows]: [DllImport("C:\\Users\\mitt\\Documents\\Visual Studio 2010\\Projects\\mrSolution\\mr\\x64\\Debug\\mrDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern bool mrEngine_initialize( [In, Out, MarshalAs(UnmanagedType.LPStruct)] PLOT_SPEC PlotSpec); [DllImport("C:\\Users\\mitt\\Documents\\Visual Studio 2010\\Projects\\mrSolution\\mr\\x64\\Debug\\mrDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern bool mrEngine_getDataPoint( [In, Out, MarshalAs(UnmanagedType.LPStruct)] PLOT_SPEC PlotSpec);

    Read the article

  • using C function in C#

    - by andrew
    i have a dll, built with mingw one of the header files contains this: extern "C" { int get_mac_address(char * mac); //the function returns a mac address in the char * mac } I use this dll in another c++ app, built using Visual C++ (2008SP1), not managed, but plain c++ (simply include the header, and call the function) But now I have to use it in a C# application The problem is that i can't figure out how exactly (i'm new in .net programming) this is what i've tried public class Hwdinfo { [DllImport("mydll.dll")] public static extern void get_mac_address(string s); } When i call the function, nothing happens (the mydll.dll file is located in the bin folder of the c# app, and it gives me no errors or warnings whatsoever)

    Read the article

  • How to marshal the type of "Cstring" in .NET Compact Framework(C#)?

    - by SmartJJ
    How to marshal the type of "Cstring" in .NET Compact Framework(C#)? DLLname:Test_Cstring.dll(OS is WinCE 5.0),source code: extern "C" __declspec(dllexport) int GetStringLen(CString str) { return str.GetLength(); } I marshal that in .NET Compact Framework(C#),for example: [DllImport("Test_Cstring.dll", EntryPoint = "GetStringLen", SetLastError = true)] public extern static int GetStringLen(string s); private void Test_Cstring() { int len=-1; len=GetStringLen("abcd"); MessageBox.Show("Length:"+len.ToString()); //result is -1,so PInvoke is unsuccessful! } The Method of "GetStringLen" in .NET CF is unsuccessful! How to marshal this type of "Cstring"? Any information about it would be very appreciated!

    Read the article

  • wglCreateContext in C# failing but not in managed C++

    - by SeeR
    I'm trying to use opengl in C#. I have following code which fails with error 2000 ERROR_INVALID_PIXEL_FORMAT First definitions: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern IntPtr GetDC(IntPtr hWnd); [StructLayout(LayoutKind.Sequential)] public struct PIXELFORMATDESCRIPTOR { public void Init() { nSize = (ushort) Marshal.SizeOf(typeof (PIXELFORMATDESCRIPTOR)); nVersion = 1; dwFlags = PFD_FLAGS.PFD_DRAW_TO_WINDOW | PFD_FLAGS.PFD_SUPPORT_OPENGL | PFD_FLAGS.PFD_DOUBLEBUFFER | PFD_FLAGS.PFD_SUPPORT_COMPOSITION; iPixelType = PFD_PIXEL_TYPE.PFD_TYPE_RGBA; cColorBits = 24; cRedBits = cRedShift = cGreenBits = cGreenShift = cBlueBits = cBlueShift = 0; cAlphaBits = cAlphaShift = 0; cAccumBits = cAccumRedBits = cAccumGreenBits = cAccumBlueBits = cAccumAlphaBits = 0; cDepthBits = 32; cStencilBits = cAuxBuffers = 0; iLayerType = PFD_LAYER_TYPES.PFD_MAIN_PLANE; bReserved = 0; dwLayerMask = dwVisibleMask = dwDamageMask = 0; } ushort nSize; ushort nVersion; PFD_FLAGS dwFlags; PFD_PIXEL_TYPE iPixelType; byte cColorBits; byte cRedBits; byte cRedShift; byte cGreenBits; byte cGreenShift; byte cBlueBits; byte cBlueShift; byte cAlphaBits; byte cAlphaShift; byte cAccumBits; byte cAccumRedBits; byte cAccumGreenBits; byte cAccumBlueBits; byte cAccumAlphaBits; byte cDepthBits; byte cStencilBits; byte cAuxBuffers; PFD_LAYER_TYPES iLayerType; byte bReserved; uint dwLayerMask; uint dwVisibleMask; uint dwDamageMask; } [Flags] public enum PFD_FLAGS : uint { PFD_DOUBLEBUFFER = 0x00000001, PFD_STEREO = 0x00000002, PFD_DRAW_TO_WINDOW = 0x00000004, PFD_DRAW_TO_BITMAP = 0x00000008, PFD_SUPPORT_GDI = 0x00000010, PFD_SUPPORT_OPENGL = 0x00000020, PFD_GENERIC_FORMAT = 0x00000040, PFD_NEED_PALETTE = 0x00000080, PFD_NEED_SYSTEM_PALETTE = 0x00000100, PFD_SWAP_EXCHANGE = 0x00000200, PFD_SWAP_COPY = 0x00000400, PFD_SWAP_LAYER_BUFFERS = 0x00000800, PFD_GENERIC_ACCELERATED = 0x00001000, PFD_SUPPORT_DIRECTDRAW = 0x00002000, PFD_DIRECT3D_ACCELERATED = 0x00004000, PFD_SUPPORT_COMPOSITION = 0x00008000, PFD_DEPTH_DONTCARE = 0x20000000, PFD_DOUBLEBUFFER_DONTCARE = 0x40000000, PFD_STEREO_DONTCARE = 0x80000000 } public enum PFD_LAYER_TYPES : byte { PFD_MAIN_PLANE = 0, PFD_OVERLAY_PLANE = 1, PFD_UNDERLAY_PLANE = 255 } public enum PFD_PIXEL_TYPE : byte { PFD_TYPE_RGBA = 0, PFD_TYPE_COLORINDEX = 1 } [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern int ChoosePixelFormat(IntPtr hdc, [In] ref PIXELFORMATDESCRIPTOR ppfd); [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern bool SetPixelFormat(IntPtr hdc, int iPixelFormat, ref PIXELFORMATDESCRIPTOR ppfd); [DllImport("opengl32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern IntPtr wglCreateContext(IntPtr hDC); And now the code that fails: IntPtr dc = Win.GetDC(hwnd); var pixelformatdescriptor = new GL.PIXELFORMATDESCRIPTOR(); pixelformatdescriptor.Init(); var pixelFormat = GL.ChoosePixelFormat(dc, ref pixelformatdescriptor); if(!GL.SetPixelFormat(dc, pixelFormat, ref pixelformatdescriptor)) throw new Win32Exception(Marshal.GetLastWin32Error()); IntPtr hglrc; if((hglrc = GL.wglCreateContext(dc)) == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //<----- here I have exception the same code in managed C++ is working HDC dc = GetDC(hWnd); PIXELFORMATDESCRIPTOR pf; pf.nSize = sizeof(PIXELFORMATDESCRIPTOR); pf.nVersion = 1; pf.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_SUPPORT_COMPOSITION; pf.cColorBits = 24; pf.cRedBits = pf.cRedShift = pf.cGreenBits = pf.cGreenShift = pf.cBlueBits = pf.cBlueShift = 0; pf.cAlphaBits = pf.cAlphaShift = 0; pf.cAccumBits = pf.cAccumRedBits = pf.cAccumGreenBits = pf.cAccumBlueBits = pf.cAccumAlphaBits = 0; pf.cDepthBits = 32; pf.cStencilBits = pf.cAuxBuffers = 0; pf.iLayerType = PFD_MAIN_PLANE; pf.bReserved = 0; pf.dwLayerMask = pf.dwVisibleMask = pf.dwDamageMask = 0; int ipf = ChoosePixelFormat(dc, &pf); SetPixelFormat(dc, ipf, &pf); HGLRC hglrc = wglCreateContext(dc); I've tried it on VIsta 64-bit with ATI graphic card and on Windows XP 32-bit with Nvidia with the same result in both cases. Also I want to mention that I don't want to use any already written framework for it. Can anyone show me where is the bug in C# code that is causing the exception?

    Read the article

  • Constants by another name

    - by Dave DeLong
    First off, I've seen this question and understand why the following code doesn't work. That is not my question. I have a constant, which is declared like; //Constants.h extern NSString * const MyConstant; //Constants.m NSString * const MyConstant = @"MyConstant"; However, in certain contexts, it's more useful to have this constant have a much more descriptive name, like MyReallySpecificConstant. I was hoping to do: //SpecificConstants.h extern NSString * const MyReallySpecificConstant; //SpecificConstants.m #import "Constants.h" NSString * const MyReallySpecificConstant = MyConstant; Obviously I cannot do this (which is explained in the linked question above). My question is: How else (besides something like #define MyReallySpecificConstant MyConstant) can I provide a single constant under multiple names?

    Read the article

  • passing array of structs from c# to regular dll

    - by buzz
    Hi there I have a regular dll with the followign fucntion exported. extern "C" __declspec(dllexport) int FindNearestStuff(double _latitude, double _longitude , LocationStruct * locations[]) LocationStruct is very simple struct LocationStruct { long positionIndex; long item; }; I'm tryign to call it from c# using [DllImport("myclever.dll", CharSet = CharSet.None)] private static extern int FindNearestStuff(double _latitude, double _longitude, ref LocationStruct [] locations); Its all cool and funky and i can step into the dll function from the debugger. Inside the dll the LocationStruct array is populated correctly and all is very good. the problem i have is when it returns back from the dll, the LocationStruct array is not coming back with the data - just empty values... what am i missing? cheers Buzz

    Read the article

  • Why does C# exit when calling the Ada elaboration routine using debug?

    - by erict
    I have a DLL created in Ada using GPS. I am dynamically loading it and calling it successfully both from Ada and from C++. But when I try to call it from C#, the program exits on the call to Elaboration init. What am I missing? The exact same DLL is perfectly happy getting called from C++ and Ada. Edit: If I start the program without Debugging, it also works with C#. But if I run it with the Debugger, then it exits on the call to ElaborationInit. There are no indications in any of the Windows event logs. If the Ada DLL is Pure, and I skip the elaboration init call, the actual function DLL is called correctly, so it has something to do with the elaboration. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace CallingDLLfromCS { class Program { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool FreeLibrary(IntPtr hModule); [UnmanagedFunctionPointer(CallingConvention.StdCall)] delegate int AdaCallable2_dlgt(int val); static AdaCallable2_dlgt fnAdaCallable2 = null; [UnmanagedFunctionPointer(CallingConvention.StdCall)] delegate void ElaborationInit_dlgt(); static ElaborationInit_dlgt ElaborationInit = null; [UnmanagedFunctionPointer(CallingConvention.StdCall)] delegate void AdaFinal_dlgt(); static AdaFinal_dlgt AdaFinal = null; static void Main(string[] args) { int result; bool fail = false; // assume the best IntPtr pDll2 = LoadLibrary("libDllBuiltFromAda.dll"); if (pDll2 != IntPtr.Zero) { // Note the @4 is because 4 bytes are passed. This can be further reduced by the use of a DEF file in the DLL generation. IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll2, "AdaCallable@4"); if (pAddressOfFunctionToCall != IntPtr.Zero) { fnAdaCallable2 = (AdaCallable2_dlgt)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(AdaCallable2_dlgt)); } else fail = true; pAddressOfFunctionToCall = GetProcAddress(pDll2, "DllBuiltFromAdainit"); if (pAddressOfFunctionToCall != IntPtr.Zero) { ElaborationInit = (ElaborationInit_dlgt)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(ElaborationInit_dlgt)); } else fail = true; pAddressOfFunctionToCall = GetProcAddress(pDll2, "DllBuiltFromAdafinal"); if (pAddressOfFunctionToCall != IntPtr.Zero) AdaFinal = (AdaFinal_dlgt)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(AdaFinal_dlgt)); else fail = true; if (!fail) { ElaborationInit.Invoke(); // ^^^^^^^^^^^^^^^^^^^^^^^^^ FAILS HERE result = fnAdaCallable2(50); Console.WriteLine("Return value is " + result.ToString()); AdaFinal(); } FreeLibrary(pDll2); } } } }

    Read the article

  • Program-wide data, C++

    - by bobobobo
    I'd like to make program-wide data in a C++ program. The easiest way to do it in C# is just public static members. C#: public static class DataContainer { public static Object data1 ; public static Object data2 ; } In C++ you can do the same thing C++ global data way#1: class DataContainer { public: static Object data1 ; static Object data2 ; } ; Object DataContainer::data1 ; Object DataContainer::data2 ; However there's also extern C++ global data way #2: class DataContainer { public: Object data1 ; Object data2 ; } ; extern DataContainer * dataContainer ; // instantiate in .cpp file Which is better, or possibly another way which I haven't thought about?

    Read the article

  • Importing a DllMain winapi .dll into Visual Studio project C++

    - by Bad Man
    I have the .def file, .lib file, the .dll, the source files. It's using WINAPI DllMain, all its functions follow that. It's like this: BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } extern "C" { int WINAPI DoSomething() { return -1; } int WINAPI DOSOMETHIGNELSE!() { return 202020; } }; IN the project settings linker I added the .lib file. There is no header file for the actual functions in the extern "C" part. I include windows.h try to call DoSomething() but doesnt know what it is.

    Read the article

  • C# & C++, runtime error when call C++ dll from C#

    - by 5YrsLaterDBA
    I have written a C++ wrapper DLL for C# to call. The DLL was tested and worked fine with my C++ test program. now integrated with C#, I got runtime error and crashed. Cannot use debugger to see more details. The C++ side has only one method: #ifdef DLLWRAPPERWIN32_EXPORTS #define DLLWRAPPERWIN32_API __declspec(dllexport) #else #define DLLWRAPPERWIN32_API __declspec(dllimport) #endif #include "NB_DPSM.h" extern "C" { DLLWRAPPERWIN32_API int WriteGenbenchDataWrapper(string fileNameToAnalyze, string parameterFileName, string baseNameToSaveData, string logFileName, string& message) ; } in the C# side, there is a definition, [DllImport("..\\..\\thirdParty\\cogs\\DLLWrapperWin32.dll")] public static extern int WriteGenbenchDataWrapper(string fileNameToAnalyze, string parameterFileName, string baseNameToSaveData, string logFileName, ref string message); and a call: string msg = ""; int returnVal = WriteGenbenchDataWrapper(rawDataFileName, parameterFileName, outputBaseName, logFileName, ref msg); I guess there must be something wrong with the last parameter of the function. string& in C++ should be ref string in C#?

    Read the article

  • initialization of objects in c++

    - by Happy Mittal
    I want to know, in c++, when does the initialization of objects take place? Is it at the compile time or link time? For ex: //file1.cpp extern int i; int j=5; //file2.cpp ( link with file1.cpp) extern j; int i=10; Now, what does compiler do : according to me, it allocates storage for variables. Now I want to know : does it also put initialization value in that storage or is it done at link time?

    Read the article

  • Preprocessor directive to test if this is C or C++

    - by Collin
    I'm trying to find a standard macro which will test whether a header file is being compiled as C or as C++. The purpose of this is that the header may be included by either C or C++ code, and must behave slightly differently depending on which. Specifically: In C, I need this to be the code: extern size_t insert (const char*); In C++, I need this to be the code: extern "C" size_t insert (const char*); Additionally, is there a way to avoid putting #ifdef's around every declaration in the header?

    Read the article

  • Use C function in C++ program; "multiply-defined" error

    - by eom
    I am trying to use this code for the Porter stemming algorithm in a C++ program I've already written. I followed the instructions near the end of the file for using the code as a separate module. I created a file, stem.c, that ends after the definition and has extern int stem(char * p, int i, int j) ... It worked fine in Xcode but it does not work for me on Unix with gcc 4.1.1--strange because usually I have no problem moving between the two. I get the error ld: fatal: symbol `stem(char*, int, int)' is multiply-defined: (file /var/tmp//ccrWWlnb.o type=FUNC; file /var/tmp//cc6rUXka.o type=FUNC); ld: fatal: File processing errors. No output written to cluster I've looked online and it seems like there are many things I could have wrong, but I'm not sure what combination of a header file, extern "C", etc. would work.

    Read the article

  • C++: static function member shared between threads, can block all?

    - by mhambra
    Hi all, I have a class, which has static function defined to work with C-style extern C { static void callback(foo bar) { } }. // static is defined in header. Three objects (each in separate pthread) are instantiated from this class, each of them has own loop (in class constructor), which can receive the callback. The pointer to function is passed as: x = init_function(h, queue_id, &callback, NULL); while(1) { loop_function(x); } So each thread has the same pointer to &callback. Callback function can block for minutes. Each thread object, excluding the one which got the blocking callback, can call callback again. If the callback function exists only once, then any thread attempting to callback will also block. This would give me an undesired bug, circa is interesting to ask: can anything in C++ become acting this way? Maybe, due to extern { } or some pointer usage?

    Read the article

  • C# wrapper of c++ dll; "Run-Time Check Failure #0 - The value of ESP was not properly saved across a

    - by Deveti Putnik
    Here is the code in C++ dll: extern "C" _declspec(dllexport) int testDelegate(int (*addFunction)(int, int), int a, int b) { int res = addFunction(a, b); return res; } and here is the code in C#: public delegate int AddIntegersDelegate(int number1, int number2); public static int AddIntegers(int a, int b) { return a + b; } [DllImport("tester.dll", SetLastError = true)] public static extern int testDelegate(AddIntegersDelegate callBackProc, int a, int b); public static void Main(string[] args) { int result = testDelegate(AddIntegers, 4, 5); Console.WriteLine("Code returned:" + result.ToString()); } When I start this small app, I get the message from the header of this post. Can someone help, please? Thanks in advance, D

    Read the article

  • static initialization order fiasco

    - by Happy Mittal
    I was reading about SIOF from a book and it gave an example : //file1.cpp extern int y; int x=y+1; //file2.cpp extern int x; y=x+1; Now My question is : In above code..will following things happen ? 1. while compiling file1.cpp, compiler leaves y as it is i.e doesn't allocate storage for it. 2. compiler allocates storage for x, but doesn't initialize it. 3. While compiling file2.cpp, compiler leaves x as it is i.e doesn't allocate storage for it. 4. compiler allocates storage for y, but doesn't initialize it. 5. While linking file1.o and file2.o, now let file2.o is initialized first, so now: Does x gets initial value of 0? or doesn't get initialized?

    Read the article

  • C++ file including C header file

    - by fdeslaur
    I need to include a C header file in my C++ project but g++ throws "not declared in this scope" errors. I read that i need to use extern "C" keyword to fix it but it didn't seem to work for me. Here is a dummy example triggering this error. main.cpp: #include <iostream> extern "C" { #include "includedFile.h" } int main() { int a = 2; int b = 1212; std::cout<< "Hello World!\n"; return 0; } includedFile.h #include <stdint.h> enum TypeOfEnum { ONE, TWO, THREE, FOUR = INT32_MAX, }; The error thrown is : $> g++ main.cpp In file included from main.cpp:4:0: includedFile.h:7:9: error: ‘INT32_MAX’ was not declared in this scope FOUR = INT32_MAX, I saw on this post that I may need #define __STDC_LIMIT_MACROS without any success. Any help is welcome!

    Read the article

  • udp through nat

    - by youllknow
    Hi everyone! I've two private networks (each of them behind a typical dsl router). The routers are connected to the WWW. The extern interface of each router have one dynamic IP address. I want to stream data via UDP directly between one client in private network A and one client in private network B. I've already tried a lot of things (see: http://en.wikipedia.org/wiki/UDP_hole_punching, or STUN). But it wasn't possible for me to transfer data between the two clients. It's possible to use a server (located in the WWW, with static IP) to transfer the extern IPs (and extern ports) from the routers between the clients. So imagine client A knows client B's external IP and client B's external port assigned by his router. I simply tried sending UDP packet to the receivers external IP/port combination, but without any result. So does anyone know what do to communicate via UDP throw the two NAT routers? It must be possible??? Or does Skype, for example, not directly communicate between the clients when the call eachother (voice over ip). I am sorry for my bad English! If something is confusing don't mind asking me!!! Thanks for your help in advance. ::::EDIT:::: I can't get pwnat or chownat working. I tried it with my own dsl-gateway - didn't work. Then I set up a complete virtual environment using VMWare. C1 (Client 1, WinXP Prof SP3): 172.16.16.100/24, GW 172.16.16.1 C2 (Client 2, WinXP Prof SP3): 10.0.0.100/24, GW 10.0.0.1 C3 (Client 3, WinXP Prof SP3): 3.0.0.2/24, GW 3.0.0.1 S1 (Ubuntu 10.04 x64 Server): eth0: 172.16.16.1/24, eth1: 1.0.0.2/24 GW 1.0.0.1 S2 (Ubuntu 10.04 x64 Server): eth0: 10.0.0.1/24, eth1: 2.0.0.2/24 GW 2.0.0.1 S3 (Ubuntu 10.04 x64 Server): eth0: 1.0.0.1/24, eth1: 2.0.0.1/24, eth2: 3.0.0.1/24 +--+ +--+ +--+ +--+ +--+ |C1|-----|S1|-----|S3|-----|S2|-----|C2| +--+ +--+ +--+ +--+ +--+ | +--+ |C3| +--+ Server S1 and S2 provide NAT functionality. (they have routing enabled and provide a firewall, which allows trafic from the internal net and provide the nat functionality) Server S3 has routing enabled. The client firewalls are turned off. C1 and C2 are able to ping C3, e.g. visit C3's webserver. They are also able to send UDP Packets to C3 (C3 successful receives them)! C1 and C2 have also webservers running for test reasons. I run ""chownat -s 80 2.0.0.2"" at C1, and ""chownat -c 8000 1.0.0.2"" at C2. Then I tried to access the Webpage from C1 via webbrower localhost at port 8000. It didn't work. Can anybody help me? Any suggestions? If you have any questions to my question, please ask!

    Read the article

  • Problem Loading a DLL (4 replies)

    I'm having some issues now that I can't see what I'm doing wrong. I'm Pinvoking a non WindowsAPI DLL (I mean, not a dll provided on windows). Pinvoking LoadLibrary, I can get a IntPtr to any WindowsAPI DLL, but never I can get a pointer to my DLL. The code I'm using is very simple, like this one: [DllImport(&quot;kernel32.dll&quot;, SetLastError true)] public static extern IntPtr LoadLibrary(); static void ...

    Read the article

  • Brute force algorithm implemented for sudoku solver in C [closed]

    - by 0cool
    This is my code that I have written in C.. It could solve certain level of problems but not the harder one.. I could not locate the error in it, Can you please find that.. # include <stdio.h> # include "sudoku.h" extern int sudoku[size][size]; extern int Arr[size][size]; int i, j, n; int BruteForceAlgorithm (void) { int val; for (i=0; i<size; i++) { for (j=0; j<size; j++) { if (sudoku[i][j]==0) { for (n=1; n<nmax; n++) { val = check (i,j,n); if ( val == 1) { sudoku[i][j]=n; // output(); break; } else if ( val == 0 && n == nmax-1 ) get_back(); } } } } } int get_back (void) { int p,q; int flag=0; for ( p=i; p>=0; p-- ) { for (q=j; q>=0; q-- ) { flag=0; if ( Arr[p][q]==0 && !( p==i && q==j) ) { if ( sudoku[p][q]== nmax-1 ) sudoku[p][q]=0; else { n = sudoku[p][q]; sudoku[p][q]=0; i = p; j = q; flag = 1; break; } } } if ( flag == 1) break; } } Code description: Sudoku.h has definitions related to sudoku solver. 1. size = 9 nmax = 10 2. check(i,j,n) returns 1 if a number "n" can be placed at (i,j) or else "0". What does this code do ? The code starts iterating from sudoku[0][0] to the end... if it finds a empty cell ( we take cell having "0" ), it starts checking for n=1 to n=9 which can be put in that.. as soon as a number can be put in that which is checked by check() it assigns it and breaks from loop and starts finding another empty cell. In case for a particular cell if it doesn't find "n" which can be assigned to sudoku cell.. it goes back to the previous empty cell and start iterating from where it stopped and assigns the next value and continues, Here comes the function get_back(). it iterates back..

    Read the article

  • Problem Loading a DLL (4 replies)

    I'm having some issues now that I can't see what I'm doing wrong. I'm Pinvoking a non WindowsAPI DLL (I mean, not a dll provided on windows). Pinvoking LoadLibrary, I can get a IntPtr to any WindowsAPI DLL, but never I can get a pointer to my DLL. The code I'm using is very simple, like this one: [DllImport(&quot;kernel32.dll&quot;, SetLastError true)] public static extern IntPtr LoadLibrary(); static void ...

    Read the article

  • Capturing Alt+PrintScreen hot key and clipboard contents

    - by kusanagi
    I setup catching hotkey on alt+printscreen. It catches perfectly but there is nothing in the buffer - no image. How can I get the image from Clipboard.GetImage() after catching hotkey? Here is the the code. using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Magic_Screenshot { public enum ModifierKey : uint { MOD_NULL = 0x0000, MOD_ALT = 0x0001, MOD_CONTROL = 0x0002, MOD_SHIFT = 0x0004, MOD_WIN = 0x0008, } public enum HotKey { PrintScreen, ALT_PrintScreen, CONTROL_PrintScreen } public class HotKeyHelper : IMessageFilter { const string MSG_REGISTERED = "??????? ??????? ??? ????????????????, ???????? UnRegister ??? ?????? ???????????."; const string MSG_UNREGISTERED = "??????? ??????? ?? ????????????????, ???????? Register ??? ???????????."; //?????? ?? ?????? ?????? singleton public HotKeyHelper() { } //public static readonly HotKeyHelper Instance = new HotKeyHelper(); public bool isRegistered; ushort atom; //ushort atom1; ModifierKey modifiers; Keys keyCode; public void Register(ModifierKey modifiers, Keys keyCode) { //??? ???????? ??? ????? ????? ? PreFilterMessage this.modifiers = modifiers; this.keyCode = keyCode; //?? ????????? ?? ??? ???????????? //if (isRegistered) // throw new InvalidOperationException(MSG_REGISTERED); //????????? atom, ??? ??????????? ?????? ??????????? atom = GlobalAddAtom(Guid.NewGuid().ToString()); //atom1 = GlobalAddAtom(Guid.NewGuid().ToString()); if (atom == 0) ThrowWin32Exception(); if (!RegisterHotKey(IntPtr.Zero, atom, modifiers, keyCode)) ThrowWin32Exception(); //if (!RegisterHotKey(IntPtr.Zero, atom1, ModifierKey.MOD_CONTROL, Keys.PrintScreen)) // ThrowWin32Exception(); //????????? ???? ? ??????? ???????? ????????? Application.AddMessageFilter(this); isRegistered = true; } public void UnRegister() { //?? ???????? ?? ??? ???????????? if (!isRegistered) throw new InvalidOperationException(MSG_UNREGISTERED); if (!UnregisterHotKey(IntPtr.Zero, atom)) ThrowWin32Exception(); GlobalDeleteAtom(atom); //??????? ???? ?? ??????? ???????? ????????? Application.RemoveMessageFilter(this); isRegistered = false; } //?????????? Win32Exception ? ????? ?? ????????? ????? ????????????? Win32 ??????? void ThrowWin32Exception() { throw new Win32Exception(Marshal.GetLastWin32Error()); } //???????, ???????????? ??? ??????????? ??????? HotKeys public event HotKeyHelperDelegate HotKeyPressed; public bool PreFilterMessage(ref Message m) { //???????? ?? ????????? WM_HOTKEY if (m.Msg == WM_HOTKEY && //???????? ?? ???? m.HWnd == IntPtr.Zero && //???????? virtual key code m.LParam.ToInt32() >> 16 == (int)keyCode && //???????? ?????? ????????????? (m.LParam.ToInt32() & 0x0000FFFF) == (int)modifiers && //???????? ?? ??????? ??????????? ????????? HotKeyPressed != null) { if ((m.LParam.ToInt32() & 0x0000FFFF) == (int)ModifierKey.MOD_CONTROL && (m.LParam.ToInt32() >> 16 == (int)Keys.PrintScreen)) { HotKeyPressed(this, EventArgs.Empty, HotKey.CONTROL_PrintScreen); } else if ((m.LParam.ToInt32() & 0x0000FFFF) == (int)ModifierKey.MOD_ALT && (m.LParam.ToInt32() >> 16 == (int)Keys.PrintScreen)) { HotKeyPressed(this, EventArgs.Empty, HotKey.ALT_PrintScreen); } else if (m.LParam.ToInt32() >> 16 == (int)Keys.PrintScreen) { HotKeyPressed(this, EventArgs.Empty, HotKey.PrintScreen); } } return false; } //??????????? Win32 ????????? ? ??????? const string USER32_DLL = "User32.dll"; const string KERNEL32_DLL = "Kernel32.dll"; const int WM_HOTKEY = 0x0312; [DllImport(USER32_DLL, SetLastError = true)] static extern bool RegisterHotKey(IntPtr hWnd, int id, ModifierKey fsModifiers, Keys vk); [DllImport(USER32_DLL, SetLastError = true)] static extern bool UnregisterHotKey(IntPtr hWnd, int id); [DllImport(KERNEL32_DLL, SetLastError = true)] static extern ushort GlobalAddAtom(string lpString); [DllImport(KERNEL32_DLL)] static extern ushort GlobalDeleteAtom(ushort nAtom); } } Where is the bug?

    Read the article

  • How to use NSMutableDictionary to store and retrieve data

    - by TechFusion
    I have created Window Based application and tab bar controller as root controller. My objective is to store Text Field data values in one tab bar VC and will be accessible and editable by other VC and also retrievable when application start. I am looking to use NSMutableDictionary class in AppDelegate so that I can access stored Data Values with keys. //TestAppDelegate.h extern NSString *kNamekey ; extern NSString *kUserIDkey ; extern NSString *kPasswordkey ; @interface TestAppDelegate :NSObject{ UIWindow *window; IBOutlet UITabBarController *rootController; NSMutableDictionary *outlineData ; } @property(nonatomic,retain)IBOutlet UIWindow *window; @property(nonatomic,retain)IBOutlet UITabBarController *rootController; @property(nonatomic,retain) NSMutableDictionary *outlineData ; @end //TestAppDelegate.m import "TestAppDelegate.h" NSString *kNamekey =@"Namekey"; NSString *kUserIDkey =@"UserIDkey"; NSString *kPasswordkey =@"Passwordkey"; @implemetation TestAppDelegate @synthesize outlineData ; -(void)applicationDidFinishLaunching:(UIApplication)application { NSMutableDictionary *tempMutableCopy = [[[NSUserDefaults standardUserDefaults] objectForKey:kRestoreLocationKey] mutableCopy]; self.outlineData = tempMutableCopy; [tempMutableCopy release]; if(outlineData == nil){ NSString *NameDefault = NULL; NSString *UserIDdefault= NULL; NSString *Passworddefault= NULL; NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObjectsAndKeys: NameDefault, kNamekey , UserIDdefault, kUserIDkey , Passworddefault, kPasswordkey , nil]; self.outlineData = appDefaults; [appDefaults release]; } [window addSubview:rootController.view]; [window makeKeyAndVisible]; NSMutableDictionary *savedLocationDict = [NSMutableDictionary dictionaryWithObject:outlineData forKey:kRestoreLocationKey]; [[NSUserDefaults standardUserDefaults] registerDefaults:savedLocationDict]; [[NSUserDefaults standardUserDefaults] synchronize]; } -(void)applicationWillTerminate:(UIApplication *)application { [[NSUserDefaults standardUserDefaults] setObject:outlineData forKey:kRestoreLocationKey]; } @end Here ViewController is ViewController of Navigation Controller which is attached with one tab bar.. I have attached xib file with ViewController //ViewController.h @interface IBOutlet UITextField *Name; IBOutlet UITextField *UserId; IBOutlet UITextField *Password; } @property(retain,nonatomic) IBOutlet UITextField *Name @property(retain,nonatomic) IBOutlet UITextField *UserId; @property(retain,nonatomic) IBOutlet UITextField *Password; -(IBAction)Save:(id)sender; @end Here in ViewController.m, I am storing object values with keys. /ViewController.m -(IBAction)Save:(id)sender{ TestAppDelegate appDelegate = (TestAppDelegate)[[UIApplication sharedApplication] delegate]; [appDelegate.outlineData setObject:Name.text forKey:kNamekey ]; [appDelegate.outlineData setObject:UserId.text forKey:kUserIDkey ]; [appDelegate.outlineData setObject:Password.text forKey:kPasswordkey]; [[NSUserDefaults standardUserDefaults] synchronize]; } I am accessing stored object using following method. -(void)loadData { TabBarAppDelegate *appDelegate = (TabBarAppDelegate *)[[UIApplication sharedApplication] delegate]; Name = [appDelegate.outlineData objectForKey:kNamekey ]; UserId = [appDelegate.outlineData objectForKey:kUserIDkey ]; Password = [appDelegate.outlineData objectForKey:kPasswordkey]; [Name release]; [UserId release]; [Password release]; } I am getting EXEC_BAD_ACCESS in application. Where I am making mistake ? Thanks,

    Read the article

  • Outlook Addin: DispEventAdvise exception.

    - by framara
    I want to creating an addin that captures when a {contact, calendar, task, note} is {created, edited, removed}. I have the following code, to make it shorter I removed all the code but the related to contact, since all types will be the same I guess. AutoSync.h class ATL_NO_VTABLE AutoSync : public wxPanel, public IDispEventSimpleImpl<1, AutoSync, &__uuidof(Outlook::ItemsEvents)>, public IDispEventSimpleImpl<2, AutoSync, &__uuidof(Outlook::ItemsEvents)>, public IDispEventSimpleImpl<3, AutoSync, &__uuidof(Outlook::ItemsEvents)> { public: AutoSync(); ~AutoSync(); void __stdcall OnItemAdd(IDispatch* Item); /* 0xf001 */ void __stdcall OnItemChange(IDispatch* Item); /* 0xf002 */ void __stdcall OnItemRemove(); /* 0xf003 */ BEGIN_SINK_MAP(AutoSync) SINK_ENTRY_INFO(1, __uuidof(Outlook::ItemsEvents), 0xf001, OnItemAdd, &OnItemsAddInfo) SINK_ENTRY_INFO(2, __uuidof(Outlook::ItemsEvents), 0xf002, OnItemChange, &OnItemsChangeInfo) SINK_ENTRY_INFO(3, __uuidof(Outlook::ItemsEvents), 0xf003, OnItemRemove, &OnItemsRemoveInfo) END_SINK_MAP() typedef IDispEventSimpleImpl<1, AutoSync, &__uuidof(Outlook::ItemsEvents)> ItemAddEvents; typedef IDispEventSimpleImpl<2, AutoSync, &__uuidof(Outlook::ItemsEvents)> ItemChangeEvents; typedef IDispEventSimpleImpl<3, AutoSync, &__uuidof(Outlook::ItemsEvents)> ItemRemoveEvents; private: CComPtr<Outlook::_Items> m_contacts; }; AutoSync.cpp _NameSpacePtr pMAPI = OutlookWorker::GetInstance()->GetNameSpacePtr(); MAPIFolderPtr pContactsFolder = NULL; HRESULT hr = NULL; //get folders if(pMAPI != NULL) { pMAPI-GetDefaultFolder(olFolderContacts, &pContactsFolder); } //get items if(pContactsFolder != NULL) pContactsFolder-get_Items(&m_contacts); //dispatch events if(m_contacts != NULL) { //HERE COMES THE EXCEPTION hr = ItemAddEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemChangeEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemRemoveEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); } somewhere else defined: extern _ATL_FUNC_INFO OnItemsAddInfo; extern _ATL_FUNC_INFO OnItemsChangeInfo; extern _ATL_FUNC_INFO OnItemsRemoveInfo; _ATL_FUNC_INFO OnItemsAddInfo = {CC_STDCALL,VT_EMPTY,1,{VT_DISPATCH}}; _ATL_FUNC_INFO OnItemsChangeInfo = {CC_STDCALL,VT_EMPTY,1,{VT_DISPATCH}}; _ATL_FUNC_INFO OnItemsRemoveInfo = {CC_STDCALL,VT_EMPTY,0}; The problems comes in the hr = ItemAddEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemChangeEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); hr = ItemRemoveEvents::DispEventAdvise((IDispatch*)m_contacts,&__uuidof(Outlook::ItemsEvents)); It gives exception in 'atlbase.inl' when executes method 'Advise': ATLINLINE ATLAPI AtlAdvise(IUnknown* pUnkCP, IUnknown* pUnk, const IID& iid, LPDWORD pdw) { if(pUnkCP == NULL) return E_INVALIDARG; CComPtr<IConnectionPointContainer> pCPC; CComPtr<IConnectionPoint> pCP; HRESULT hRes = pUnkCP->QueryInterface(__uuidof(IConnectionPointContainer), (void**)&pCPC); if (SUCCEEDED(hRes)) hRes = pCPC->FindConnectionPoint(iid, &pCP); if (SUCCEEDED(hRes)) //HERE GIVES EXCEPTION //Unhandled exception at 0x2fe913e3 in OUTLOOK.EXE: 0xC0000005: //Access violation reading location 0xcdcdcdcd. hRes = pCP->Advise(pUnk, pdw); return hRes; } I can't manage to understand why. Any sugestion here? Everything seems to be fine, but obviously is not. I've been stucked here for quite a long time. Need your help, thanks.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >